完全符合要求的作业
Topic source运行到最后一个测试报错,报错信息如下:
Traceback (most recent call last):
File "e:\PY代码\练习\去字符串首尾空格.py", line 20, in <module>
elif trim(' ') != '':
File "e:\PY代码\练习\去字符串首尾空格.py", line 5, in trim
s=trim(s[1:])
File "e:\PY代码\练习\去字符串首尾空格.py", line 5, in trim
s=trim(s[1:])
File "e:\PY代码\练习\去字符串首尾空格.py", line 5, in trim
s=trim(s[1:])
File "e:\PY代码\练习\去字符串首尾空格.py", line 6, in trim
if s[-1]==' ' or s[-1]=='\t':
IndexError: string index out of range
源代码:
def trim(s):
if len(s)==0:
return s
if s[0]==' ' or s[0]=='\t':
s=trim(s[1:])
if s[-1]==' ' or s[-1]=='\t':
s=trim(s[:-2])
return s
- 1
魅影迷惑你
def trip(s):
#使用递归,清除字符串头部空白区域
if len(s) == 0:
return s
if s[0]==' ' or s[0]=='\t': # 考虑到空白有“space”和“tab”两种情况
s=trip(s[1:]) # 先清除头部空白
if s[-1]==' ' or s[-1]=='\t':
s=trip(s[:-2]) # 再去除尾部空白
return s