Discuss / Python / 多种表达均可

多种表达均可

Topic source

代码片段:

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

    raise TypeError('please give a string type')

TypeError: please a str type

哈哈哈,你这个不但去首尾空了,还反向了。


  • 1

Reply