`
384444165
  • 浏览: 256352 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

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 = [1,2,3,4]
>>> 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'

 

0
2
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics