码迷,mamicode.com
首页 > 编程语言 > 详细

2-python代码坑点

时间:2018-07-11 14:35:28      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:list   否则   递归   判断   就会   hello   取出   成功   trim   

#切片:
# L = [‘aaa‘, ‘bbb‘, ‘ccc‘, ‘ddd‘]
# print(L[1 : 3])  #取[1, 3):下标
# L = list(range(100))
# print(L[:10])
# print(L[-10:])
# 
# print(L[2:10:4])       #从2开始取,步长为4,小于10
# # [2, 6]
# print(‘abcdefg‘[:3])
# # abc
# print(‘abcdefg‘[::2])
# # aceg


#取出字符串的首位空格的函数
# def trim(s):
#     if s == ‘‘:
#         return ‘‘
#     len1 = len(s)
#     i = 0
#     j = len1 - 1
#     while i < len1  and s[i] == ‘ ‘:
#         i += 1
#         print(i)
#     while j > 0 and s[j] == ‘ ‘ :
#         j -= 1
#         print(j)
#     if i <= j:
#         print(i, (j))
#         return s[i:j+1]
#     else:
#         return ‘‘ 
    
#递归写法:
# def trim(s):
#     if s == ‘‘:
#         return s
#     if s[:1] == ‘ ‘:
# #     if s[0] == ‘ ‘:
#         return trim(s[1:])
#     if s[-1:] == ‘ ‘:
# #     if s[-1] == ‘ ‘:
#         return trim(s[:-2])
#     else:
#         return s
#递归写法2:
def trim(s):
    if s == ‘‘:
        return s
    if s[0] == ‘ ‘:
        s = trim(s[1: ])   #如果这里不用返回值的话,必须要在下面判空,否则可能s已经为空了,再去做下一个if判断,就会越界
#         return trim(s[1: ])
    if s == ‘‘:            
        return s
    if s[-1] == ‘ ‘:
        s = trim(s[ :-2])
#         return trim(s[ :-2])
    return s   
#     
# # 测试:
t = [1, 2, 3, 4, 5]
print(t[:-2])

if trim(‘ ‘) != ‘‘:
    print(‘ys‘ + trim(‘    hello‘) + ‘ys‘)
    print(‘no‘)
# 
if trim(‘hello  ‘) != ‘hello‘:
    print(‘a‘ + trim(‘hello  ‘) + ‘b‘)
    print(‘1测试失败!‘)
elif trim(‘  hello‘) != ‘hello‘:
    print(‘2测试失败!‘)
elif trim(‘  hello  ‘) != ‘hello‘:
    print(‘3测试失败!‘)
elif trim(‘  hello  world  ‘) != ‘hello  world‘:
    print(‘4测试失败!‘)
elif trim(‘‘) != ‘‘:
    print(‘5测试失败!‘)
elif trim(‘    ‘) != ‘‘:
    print(‘6测试失败!‘)
else:
    print(‘测试成功!‘)

  

2-python代码坑点

标签:list   否则   递归   判断   就会   hello   取出   成功   trim   

原文地址:https://www.cnblogs.com/zhumengdexiaobai/p/9293602.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!