学习python切片时,是编写函数可以做到去除字符串前后的空格,代码如下:
def trim(s):
while s[:1]==' ':
s=s[1:]
while s[-1:]==' ':
s=s[:-1]
return s
测试没有问题,但是想到,如果字符串是" " (即单独的一个空格)应该会进入死循环,但是并没有
问题一:为什么没进入死循环
问题二:后面自己改了一下代码如下:
def trim(s):
while s[0]==" ":
if len(s)==1:
s=" "
break
s=s[1:]
while s[-1]==" ":
if len(s)==1:
s=" "
break
s=s[:-1]
return s
测试发现可以单独通过字符串" "的。但是当我用这种方式:
if trim('hello ') != 'hello':
print('测试失败!')
elif trim(' hello') != 'hello':
print('测试失败!')
elif trim(' hello ') != 'hello':
print('测试失败!')
elif trim(' hello world ') != 'hello world':
print('测试失败!')
elif trim('') != '':
print('测试失败!')
elif trim(' ') != '':
print('测试失败!')
else:
print('测试成功!')
发现会出现报错,报错为:
File "c:\Users\zdw\Desktop\python\study\qiepian.py", line 23, in <module>
elif trim('') != '':
File "c:\Users\zdw\Desktop\python\study\qiepian.py", line 2, in trim
while s[0]==" ":
IndexError: string index out of range
问题二:为什么第二种单独测试字符串" "不会报错,而统一测试会报错
谢谢大家。刚开始学python,理论理解不清