Python3,字符串函数整理

rsplit从后往前分割

>>> "banana".split("n",1)
['ba', 'ana']
>>> "banana".rsplit("n",1)
['bana', 'a']

capitalize首字母大写

>>> 'GrEat'.capitalize()
'Great'

casefold:lower() 方法只对ASCII编码,也就是‘A-Z’有效,对于其他语言(非汉语或英文)中把大写转换为小写的情况只能用 casefold() 方法。

>>> 'GreaTEr'.casefold()
'greater'

非字母后的第一个字母将转换为大写字母

>>> "This is a 3g3g".title()
'This Is A 3G3G'

center,ljust,rjust

>>> "great".center(20, '*')
'*******great********'
>>> "great".ljust(20, '*')
'great***************'
>>> "great".rjust(20, '*')
'***************great'

count计数

"This is a dog".count("s")
2

expandtabs制表符转换为空格

>>> '\t'.expandtabs()
'        '
>>> '\t\t'.expandtabs()
'                '

partition、rpartition分割成三个元素并放入到元组中

>>> "This is a pig".partition("is")
('Th', 'is', ' is a pig')
>>> "This is a pig".rpartition("is")
('This ', 'is', ' a pig')

index,该方法与 python find()方法一样,只不过如果str不在 string中会报一个异常。

>>> 'This is a dog'.index("i", 4, 10)
5

swapcase大小写转换

>>> "GrEat".swapcase()
'gReAT'

translate,先做翻译表

>>> intab = "aeiou"
>>> outtab = "12345"
>>> trantab = str.maketrans(intab, outtab)   # 制作翻译表
>>> str = "this is string example....wow!!!"
>>> print (str.translate(trantab))
th3s 3s str3ng 2x1mpl2....w4w!!!

startswith。endswith

>>> "greater".startswith("great")
True
>>> "greater".endswith("er")
True

format_map,与format类似

>>> People = {"name": "john", "age": 33}
>>> print("My name is {name},iam{age} old".format_map(People))
My name is john,iam33 old

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值