def trim(strs):
if not isinstance(strs,(str)):
raise TypeError('please give a string type')
if strs[:1]==' ':#第一个是不是空
return trim(strs[1:])
if strs[:-2:-1]==' ':#strs[:-2:-1]或者strs[-1:]==' ' #最后一个是不是空 多种写法
return trim(strs[-2::-1]) #或者trim(strs[:-1])
return strs
运行结果:
>>> from python1 import trim
>>> trim(' 123 ')
'321'
>>> trim(' 123 ')
'321'
>>> trim('1 23 ')
'32 1'
>>> trim(' 1 23 ')
'32 1'
>>> trim(1234)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "E:\lily\python\python1.py", line 62, in trim
用户6130214994
代码片段:
运行结果:
>>> from python1 import trim
>>> trim(' 123 ')
'321'
>>> trim(' 123 ')
'321'
>>> trim('1 23 ')
'32 1'
>>> trim(' 1 23 ')
'32 1'
>>> trim(1234)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "E:\lily\python\python1.py", line 62, in trim
raise TypeError('please give a string type')
TypeError: please a str type