def trim(s): while s[:1]==' ': s=s[1:] while s[-1:]==' ': s=s[:-1] return s
測試沒有問題,但是想到,如果字符串是" " (The separate a space)Should be able to enter infinite loop,但是並沒有
問題一:Why didn't enter the infinite loop
問題二:Behind your change the code as follows:
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
Tests found that can be individually by string" "的.But when I use this way:
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('測試成功!')
Found that there will be an error,報錯為:
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
問題二:Why the second test string alone" "不會報錯,And unified test, an
謝謝大家.剛開始學python,Theoretical understanding is not clear