第三章 使用字符串

3.2设置字符串的格式:精简版

#类似C语言的printf,在%的左边指定一个字符串,在右边指定要设置其格式的值(元组和字典,主要是元组)
>>>format="hello,%s .%s enough for ya?"
>>>values=('world','Hot')
>>>format % values
'hello,world.Hot enough for ya?'

#新代码,替换字段没有名称或者用索引
>>>"{},{} and {}".format('first','second','third')
'first','second','third'
>>>"{0},{1} and {2}".format('first','second','third')
'first','second','third'

3.3设置字符串格式:完整版

#要将未命名字段按顺序放在前面
>>>print('{bar}, {} {foo} {}'.format('i','you.',bar='Hello',foo='love'))
Hello, i love you.

#转换标志:跟在感叹号后面的单个字符,包括r、s、a等,见书本P44
>>>print('{pi!s}{pi!r}{pi!a}'.format(pi='π'))
π 'π' '\u03c0'

3.3.3宽度、精度和千位分隔符

#宽度,使用<>^分别表示左右居中对齐,并可以在宽度和精度前面添加填充标志
>>>print('{:<10.2f}\n{:>010.2f}'.format(3.14159,3.14159))
3.14      
0000003.14

#你可以使用填充字符来扩充对齐说明符,此时不是使用默认的空格
>>>print('{:¥<10.2f}\n{:&>010.2f}'.format(3.14159,3.14159))
3.14¥¥¥¥¥¥
&&&&&&3.14

#可以使用更具体的说明符=,它将填充字符放在符号和数字之间
>>>print('{:$=10.2f}'.format(-3.1415))
-$$$$$3.14

3.4字符串方法

#center,在两边填充字符让字符串居中
>>>print(' hello'.center(10,'*'))
** hello**

#find,与index基本相同,查找子串并返回第一个符合的索引,没有则返回-1
>>>print('hello'.find('l'))
2
>>>print('hello'.find('q'))
-1

#strip,删除开头末尾的空白,也可以指定删除哪些字符,但只能是开头和末尾的,并返回删除后的值
>>>print('  hello '.strip())
hello
>>>print('*  hel*lo *'.strip('*'))
  hel*lo 

#lower,返回字符串的小写版本

#replace,指定子串替换成另外一个字符串
>>>print('hello'.replace('ll','m'))
hemo

#join,用于合并序列的元素
>>>a=['1','2','3']
>>>'+'.join(a)
1+2+3

#split,用于分割字符串,如果没有指定分隔符,则在连续空白处分割
>>>a='1+2+3'
>>>a.split('+')
['1', '2', '3']
>>>a='1 2 3'
>>>a.split('+')
['1', '2', '3']

#translate,可以同时替换多个字符,使用前要创建转换表,使用maketrans来创建转换表
>>>table=str.maketrans('cs','kz')
>>>'cs'.translate(table)
kz
#maketrans接受第三个参数,指定将哪些字符删除
>>>table=str.maketrans('cs','kz',' ')
>>>'cs   sc'.translate(table)
kzzk

3.4.9判断字符串是否满足特定的条件

isspace  isdigit   isupper

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值