码迷,mamicode.com
首页 > 编程语言 > 详细

python 字符串操作

时间:2019-04-19 00:52:39      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:lines   一段   char   操作   变量命名   首字母   --   example   title   

name.capitalize() 首字母大写
name.casefold() 大写全部变小写
name.center(50,"-") 输出 ‘---------------------Alex Li----------------------‘
name.count(‘lex‘) 统计 lex出现次数
name.encode() 将字符串编码成bytes格式
name.endswith("Li") 判断字符串是否以 Li结尾
"Alex\tLi".expandtabs(10) 输出‘Alex Li‘, 将\t转换成多长的空格
name.find(‘A‘) 查找A,找到返回其索引, 找不到返回-1

format :
>>> msg = "my name is {}, and age is {}"
>>> msg.format("alex",22)
‘my name is alex, and age is 22‘
>>> msg = "my name is {1}, and age is {0}"
>>> msg.format("alex",22)
‘my name is 22, and age is alex‘
>>> msg = "my name is {name}, and age is {age}"
>>> msg.format(age=22,name="ale")
‘my name is ale, and age is 22‘
format_map
>>> msg.format_map({‘name‘:‘alex‘,‘age‘:22})
‘my name is alex, and age is 22‘


msg.index(‘a‘) 返回a所在字符串的索引
‘9aA‘.isalnum() True

‘9‘.isdigit() 是否整数
name.isnumeric 是否数字
name.isprintable
name.isspace
name.istitle
name.isupper
"|".join([‘alex‘,‘jack‘,‘rain‘])
‘alex|jack|rain‘


maketrans
>>> intab = "aeiou" #This is the string having actual characters.
>>> outtab = "12345" #This is the string having corresponding mapping character
>>> trantab = str.maketrans(intab, outtab)
>>>
>>> str = "this is string example....wow!!!"
>>> str.translate(trantab)
‘th3s 3s str3ng 2x1mpl2....w4w!!!‘

msg.partition(‘is‘) 输出 (‘my name ‘, ‘is‘, ‘ {name}, and age is {age}‘)

>>> "alex li, chinese name is lijie".replace("li","LI",1)
‘alex LI, chinese name is lijie‘

msg.swapcase 大小写互换


>>> msg.zfill(40)
‘00000my name is {name}, and age is {age}‘

 

>>> n4.ljust(40,"-") 长度40,不够用-在右边补上
‘Hello 2orld-----------------------------‘
>>> n4.rjust(40,"-") 长度40,不够用-在左边补上
‘-----------------------------Hello 2orld‘


>>> b="ddefdsdff_哈哈"
>>> b.isidentifier() #检测一段字符串可否被当作标志符,即是否符合变量命名规则
True

 

 

‘Jason‘.lower() #所有字母小写
‘Jason‘.upper() #所有字母大写
‘Jason‘.swapcase() #大小写互换

‘\nJason‘.lstrip() #去除左边的空格、换行
‘\nJason‘.rstrip() #去除右边的空格、换行
‘\nJason\n‘.strip() #去除两 边的空格、换行


p = str.maketrans(‘abcdef‘,‘123456‘)
print(‘jason‘.translate(p)) #例子:将字符串左边的abcdef相对应替换右边的数字

‘Jason‘.replace(‘J‘,‘x‘) #字符串替换,可以加第三个参数【数字】,替换数量

‘Jason‘.rfind(‘a‘) #查找字符串,从左往右边开始数
‘Jason‘.split(‘a‘) #字符串以特定字符进行分割

‘Jas\non‘.splitlines() #根据换行字符进行分割

‘jason liu‘.title() #首字母大写,变成标题

 

python 字符串操作

标签:lines   一段   char   操作   变量命名   首字母   --   example   title   

原文地址:https://www.cnblogs.com/jasonLiu2018/p/10733381.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!