刘伟 发表于 2017-5-7 12:41:01

Beginning Python 笔记学API —— Chapter3 使用字符串

  1、格式化

>>> from math import pi
>>> '%10f' % pi
'3.141593'
>>> '%10f' % pi    # 字段宽10
'3.141593'
>>> '%10.2f' % pi    #字段宽10,精度2
'      3.14'
>>> '%.5s' % 'Hello world'
'Hello'
>>> '%010.2f' % pi   #宽度为10,其余位用0填充
'0000003.14'
  2、字符串方法

>>> subject = '$$$ Get rich now!!! $$$'
>>> subject.find('$$$')
0
>>> subject.find('$$$',1)
20
>>> subject.find('!!!')
16
>>> subject.find('!!!',0,16)
-1
>>> # join 是split的逆操作
>>> seq =
>>> sep = '+'
>>> sep.join(seq)
Traceback (most recent call last):
File "<pyshell#67>", line 1, in <module>
sep.join(seq)
TypeError: sequence item 0: expected string, int found
>>> seq = ['1','2','3','4']
>>> sep.join(seq)
'1+2+3+4'
# strip 返回去除两侧空格的字符串
>>> '   hello world   '.strip()
'hello world'
>>> # translate 不同于replace处为只处理单个字符,但可以批量
>>> from string import maketrans
>>> table = maketrans('cs','kz')
>>> 'this is an incredible test'.translate(table)
'thiz iz an inkredible tezt'
页: [1]
查看完整版本: Beginning Python 笔记学API —— Chapter3 使用字符串