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'

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值