利用切片操作,實現一個trim()函數,去除字符串首尾的空格,注意不要調用str的strip()
方法:
#!/usr/bin/env python3 def trim(s): if(s==None or s == ''): return '' # 左側空格 while(s[:1] == ' ' ): s = s[1:] # 右側空格 while(s[-1:] == ' ' ): s = s[:-1] return s
測試數據
if trim('hello ') != 'hello': 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('測試成功!')