python 字符串操作
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']
6. 格式化
- %s 字符串 (采用str()的显示)
- %r 字符串 (采用repr()的显示)
- %c 单个字符
- %b 二进制整数
- %d 十进制整数
- %i 十进制整数
- %o 八进制整数
- %x 十六进制整数
- %e 指数 (基底写为e)
- %E 指数 (基底写为E)
- %f 浮点数
- %F 浮点数,与上相同
- %g 指数(e)或浮点数 (根据显示长度)
可以用如下的方式,对格式进行进一步的控制:
%[(name)][flags][width].[precision]typecode
(name)为命名
flags可以有+,-,' '或0。+表示右对齐。-表示左对齐。' '为一个空格,表示在正数的左侧填充一个空格,从而与负数对齐。0表示使用0填充。
width表示显示宽度
precision表示小数点后精度
比如:
print("%+10x" % 10) print("%04d" % 5) print("%6.3f" % 2.3)
上面的width, precision为两个整数。我们可以利用*,来动态代入这两个量。比如:
print("%.*f" % (4, 1.2))
Python实际上用4来替换*。所以实际的模板为"%.4f"。