【Python3】字符串操作

name='my name is jack'
name.capitalize() #首字母大写 name.casefold() #大写全部变小写 name.center(
50,"-") #输出 '-------------my name is jack--------------',共50个字符 name.count('a') #统计a出现次数 name.encode() #将字符串编码成bytes格式 name.endswith("k") #判断字符串是否以a结尾 "my\tname".expandtabs(10) #输出'my name', 将\t转换成多长的空格 name.find('jack') #查找jack,找到返回其索引(首位置),找不到返回-1
name.rfind('a')  #查找最右边的'a' format : >>> msg = "my name is {}, and age is {}" >>> msg.format("jack",22) 'my name is jack, and age is 22' >>> msg = "my name is {1}, and age is {0}" >>> msg.format(22,"jack") 'my name is jack, and age is 22' >>> msg = "my name is {name}, and age is {age}" >>> msg.format(name="jack",age=22) 'my name is jack, and age is 22' format_map >>> msg.format_map({'name':'alex','age':22}) 'my name is alex, and age is 22' 'banana'.index('a') #返回a所在字符串的索引 '9aA'.isalnum() True #是否是英文或数字
'9aA!'.isalnum()  False '9aA'.isalpha()  True #是否是英文
'1B'.isdecimal()  True #是否是16进制
'9'.isdigit() #是否整数
'abc'.islower()  True #是否全小写
'ABC'.isupper()  True #是否全大写 '123'.isnumeric() True #是否纯数字
'2A'.isnumeric()  False
驱动程序.isprintable()  False ' '.isspace #是否空格 'My Name Is Jack'.istitle()  True #每个单词首字母是否大写
'My name is jack'.istitle()  False
>>>"|".join(['sandra','jack','happy']) 'sandra|jack|happy' maketrans #定义字符转换规则,和translate一起用 >>> intab = "aeiou" #This is the string having actual characters. >>> outtab = "12345" #This is the string having corresponding mapping character >>> transtab = str.maketrans(intab, outtab) >>> str = "this is string example" >>> str.translate(transtab) 'th3s 3s str3ng 2x1mpl2'
msg.partition(
'is') 输出 ('my name ', 'is', ' {name}, and age is {age}') >>> "jack, chinese name is xu".replace("jack","sandra",1) #默认全部替换
'sandra, chinese name is xu'
msg.swapcase 大小写互换
>>> msg.zfill(50) #'0'填充 '00000my name is {name}, and age is {age}' >>> 'Hello World'.ljust(50,"-") 'Hello World-----------------------------' >>> 'Hello World'.rjust(50,"-") '-----------------------------Hello World' >>>'Jack'.lower() #改小写
'jack'
>>>'jACK'  #改大写
'JACK'
>>> b="name" >>> b.isidentifier() #检测一段字符串可否被当作标志符,即是否符合变量命名规则 True

>>>'\n jack\n'.strip() #去掉两端的空格和换行
jack
>>>'\njack'.lstrip()
>>>'jack\n'.rstrip()

>>>'1+2+3+4+5'.split('+')  #得到列表
['1','2','3','4','5']
>>>'1+2+3\n+4+5'.splitlines()  #按换行符分,得到列表
['1+2+3','+4+5']

 

posted @ 2017-10-23 14:56  生信杰克  阅读(208)  评论(0编辑  收藏  举报