#切片:
# 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('测试成功!')