您的位置:首页 > 编程语言 > Python开发

Recipe 1.7. Reversing a String by Words or Characters(Python Cookbook)

2010-12-19 14:21 363 查看
reverse 1 >>> astring = "hello ray"
2 >>> revwords = astring.split()
3 >>> revwords
4 ['hello', 'ray']
5 >>> revwords.reverse()
6 >>> revwords
7 ['ray', 'hello']
8 >>> revwords = ' '.join(revwords)
9 >>> revwords
'ray hello'
>>> import re
>>> revwords = re.split(r'(\s+)', astring)
>>> revwords
['hello', ' ', 'ray']
>>> revwords.reverse()
>>> revwords
['ray', ' ', 'hello']
>>> revwords = ''.join(revwords)
>>> revwords
'ray hello'
>>> revwords = ''
>>> revwords = ''.join(reversed(astring))
>>> revwords
'yar olleh'
>>> revwords = ''.join(reversed(astring.split()))
>>> revwords
'rayhello'
>>> revwords = ' '.join(reversed(astring.split()))
>>> revwords
'ray hello'
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐