python文本 字符串逐字符反转以及逐单词反转
场景:
字符串逐字符反转以及逐单词反转
首先来看字符串逐字符反转,由于python提供了非常有用的切片,所以只需要一句就可以搞定了
>>> a='abc edf degd'
>>> a[::-1]
'dged fde cba'
>>>
然后我们来看住单词反转
1.同样的我们也可以使用切片
>>> a.split ()[::-1]
['degd', 'edf', 'abc']
2.可以使用原生方法reverse
>>> result=a.split()
>>> result
['abc', 'edf', 'degd']
>>> result.reverse()
>>> result=' '.join (result)
'degd edf abc'
在反转的过程中,我意外发现join的另外使用方法
>>> a='abcd'
>>> ' '.join (a)
'a b c d'
'a b c e d f d e g d'
>>>