本文是廖雪峰Python教學(xué)切片章節(jié)的課后習(xí)題
利用切片操作,實(shí)現(xiàn)一個(gè)trim()函數(shù)携狭,去除字符串首尾的空格继蜡,注意不要調(diào)用str的strip()方法:
# 測試:
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('測試成功!')
trim() 函數(shù)的功能就是移除首尾空格,實(shí)現(xiàn)功能需要添加判斷逛腿,然后進(jìn)行遞歸壹瘟,代碼如下:
#利用切片操作,實(shí)現(xiàn)一個(gè)trim()函數(shù)
#使用遞歸函數(shù)
def trim(s):
if s=='':
return s
elif (s[0]!=' ') and (s[-1]!=' '):
return s
elif s[0]==' ':
return trim(s[1:])
else:
return trim(s[0:-1])
def main():
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('測試成功!')
if __name__ == '__main__':
main()