python切片 利用切片操作,實現一個trim()函式,去除字串首尾的空格,注意不要呼叫str的strip()方法

hdytto發表於2018-07-22
def trim(s):
    '''首先判斷該字串是否為空,如果為空,就返回該字串,
    如果不為空的話,就判斷字串首尾字元是否為空,
    如果為空,就使用遞迴再次呼叫該函式trim(),否則就返回該函式'''
    if len(s) == 0:
        return s
    elif s[0] == ' ':
        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('測試成功!')

 

相關文章