程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Understanding of the use of the or function of python slices

編輯:Python
學習python切片時,Is to write functions can be done to remove a string of Spaces before and after,代碼如下:
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


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved