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'
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'
相关文章推荐
- Recipe 1.4. Reversing a String by Words or Characters
- Recipe 1.11. Checking Whether a String Is Text or Binary(Python Cookbook)
- Recipe 1.10. Filtering a String for a Set of Characters(Python Cookbook)
- Recipe 1.8. Checking Whether a String Contains a Set of Characters(Python Cookbook)
- Recipe 1.1. Processing a String One Character at a Time(Python Cookbook)
- Python Cookbook 第二版 汉化版 [Recipe 1.3] 测试一个对象是否为 String-like 对象
- Recipe 1.3. Testing Whether an Object Is String-like(Python Cookbook)
- Recipe 1.5. Trimming Space from the Ends of a String(Python Cookbook)
- Recipe 1.2. Converting Between Characters and Numeric Codes(Python Cookbook)
- Python Cookbook 第二版 汉化版 [Recipe 1.7] 以单词或字符为单位对字符串进行反序排列
- Python Cookbook 第二版 汉化版 [Recipe 1.3] 测试一个对象是否为 String-like 对象
- Python Cookbook 第二版 汉化版 [Recipe 1.7] 以单词或字符为单位对字符串进行反序排列
- Python Cookbook 第二版 汉化版 [Recipe 1.2] 字符与其对应的数字编码之间的转换
- Python Cookbook 第二版 汉化版 [Recipe 1.4] 对齐字符串
- Stemming the words and word lemmatization —— Python Data Science CookBook
- Python Cookbook 第二版 汉化版 [Recipe 1.8] 检测字符串是否包含特定的字符集合
- Python Cookbook 第二版 汉化版 [Recipe 1.6] 字符串的组合
- Python Cookbook 第二版 汉化版 [Recipe 1.5] 去除字符串末尾的空格
- Recipe 1.9. Simplifying Usage of Strings' translate Method(Python Cookbook)
- Recipe 1.12. Controlling Case(Python Cookbook)