利用切片操作,實現一個trim()函式,去除字串首尾的空格,注意不要呼叫str的strip()方法:
阿新 • • 發佈:2018-11-22
1,首先判斷字串是否是空,如果是直接返回字串;
2,迴圈判斷字串從第一個開始是否是空格,如果是則去掉空格,每次去掉空格後判斷剩下的是否是空,如果是返回字串
3,迴圈判斷字串從最後一個開始往前是否是空格,如果是則去掉空格,每次去掉空格後判斷剩下的是否是空,如果是返回字串
4,空格都去掉後返回字串。
程式碼實現:
def trim(s): if len(s) == 0: return s else: while s[0] == ' ': s = s[1:] if len(s) == 0: return s while s[-1] == ' ': s = s[:-2] if len(s) == 0: return s 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('測試成功!')
執行結果:
測試成功!