python案例 - 實現trim函數


利用切片操作,實現一個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('測試成功!')

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM