Ray's playground

 

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

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
10 'ray hello'
11 >>> import re
12 >>> revwords = re.split(r'(\s+)', astring)
13 >>> revwords
14 ['hello'' ''ray']
15 >>> revwords.reverse()
16 >>> revwords
17 ['ray'' ''hello']
18 >>> revwords = ''.join(revwords)
19 >>> revwords
20 'ray hello'
21 >>> revwords = ''
22 >>> revwords = ''.join(reversed(astring))
23 >>> revwords
24 'yar olleh'
25 >>> revwords = ''.join(reversed(astring.split()))
26 >>> revwords
27 'rayhello'
28 >>> revwords = ' '.join(reversed(astring.split()))
29 >>> revwords
30 'ray hello'

 

posted on 2010-12-19 14:21  Ray Z  阅读(156)  评论(0编辑  收藏  举报

导航