python 字符串操作
2015-12-23 14:41
671 查看
1. 字符串连接
2. 字符串替换
3. 字符串反转
4. 编码
5. 拆分
# join a = ['a','b','c','d'] content = ''.join(a) # 'abcd' # 替换占位符 test_str = 'Hello %s! Welcome to %s'%('Tom', 'our home') # tuple content = '%s%s%s%s'%tuple(a) # abcd # format test_str = 'Hello %(name)s! Welcome to %(addr)s' d = {'name':'Tom', 'addr':'our home'} test_str % d test_str = 'Hello {name}! Welcome to {addr} {0}' test_str.format('^^', name='Tom', addr='our home')
2. 字符串替换
a = 'hello word' b = a.replace('word','python') print b # hello python import re a = 'hello word' strinfo = re.compile('word') b = strinfo.sub('python',a) print b # hello python
3. 字符串反转
a = 'abcd' b = a[::-1]##[::-1]通过步进反转 print b b = list(a) b.reverse() ''.join(b)
4. 编码
a = '你好' b = 'python' print a.decode('utf-8').encode('gbk')##decode方法把字符串转换为unicode对象,然后通过encode方法转换为指定的编码字符串对象 print b.decode('utf-8')##decode方法把字符串转换为unicode对象
5. 拆分
a='hello world' b = a.split() # ['hello', 'world']
相关文章推荐
- [LeetCode]题解(python):075-Sort Colors
- 每天学点Python之strings
- 每天学点Python之comprehensions
- Python模块
- Python基础教程 第11章: 文件和流 学习笔记
- 学好 Python 的 11 个优秀资源
- Python进阶09 动态类型
- [LeetCode]题解(python):074-Search a 2D Matrix
- Python进阶08 异常处理
- Python进阶07 函数对象
- Python进阶06 循环对象
- Python进阶05 循环设计
- Python进阶04 函数的参数对应
- Python进阶03 模块
- Python进阶02 文本文件的输入输出
- Python进阶01 词典
- [LeetCode]题解(python):073-Set Matrix Zeroes
- python timeit
- python datetime strftime格式变换
- [LeetCode]题解(python):072-Edit Distance