标签:
1. 字符串连接
# 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‘]
标签:
原文地址:http://www.cnblogs.com/snow-backup/p/5069916.html