1. 程式人生 > >利用切片操作,實現一個trim()函式,去除字串首尾的空格

利用切片操作,實現一個trim()函式,去除字串首尾的空格

非遞迴的方法:

def trim(s):
    while(s[:1]==' '):
        s=s[1:]
    while(s[-1:]==' '):
        s=s[:-1]
    return s

遞迴的方法:

def trim(s):
    if len(s)==0:
        return s
    elif s[:1]==' ':
        return trim(s[1:])
    elif s[-1:]==' ':
        return trim(s[:-1])
    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('測試成功!')