Python字符串常⽤函数详解
字符串相关操作⼤致总结以下9个部分,包括常⽤字符集合、⼤⼩写转换、判断字符元素类型、字符填充、字符串搜索、字符串替换、字符串添加、字符串修剪以及字符串分割。'字符串相关函数'
'1.字符串常量集合'
import string
print(string.ascii_uppercase) #⼤写字母
print(string.ascii_lowercase) #⼩写字母
print(string.ascii_letters)  #⼤⼩写字母
print(string.digits)          #数字
字符串复制函数print(string.punctuation)    #符号集合
print(string.printable)      #可输⼊字符合集,包括⼤⼩写字母数字和符号的合集
'2.字符串⼤⼩写转换 5个'
str='hello,woRld!'
print(str.capitalize()) #仅⾸字母⼤写,Hello,world!
print(str.title())      #仅每个单词⾸字母⼤写,Hello,World!
print(str.upper())      #每个字母都⼤写,HELLO,WORLD!
print(str.lower())      #每个字母都⼩写,hello,world!
print(str.swapcase())  #⼤⼩写互换,HELLO,WOrLD!
'3.字符串内容判断 10个'
num='123'
alp='asd'
num_alp='a1s2d'
printable='`~!@#$%'
print(num.isdigit())            #字符串中的字符是否都是数字,True
print(alp.isalpha())            #字符串中的字符是否都是字母,True
print(num_alp.isalnum())        #字符串中的字符是否都是字母和数字,True
print(printable.isprintable())  #字符串中的字符是否都是可输⼊字符,True
print(num.isnumeric())          #字符串中的字符是否都是数字,True
print(alp.islower())            #字符串中的字符是否都是⼩写字母,True
print(num_alp.isupper())        #字符串中的字符是否都是⼤写字母,False
print(alp.istitle())            #字符串中的字符是形如标题Hello World,False
print(' '.isspace())            #字符串中的字符是否都是空格,True
print('哈'.isascii())            #字符串中的字符是否可⽤ascll码表⽰,汉字是Unicode编码表⽰的所以是False
'4.字符串填充'
str='Welcome'
(13,'*'))#***Welcome***
print(str.ljust(10,'+')) #Welcome+++
print(str.rjust(10,'-')) #---Welcome
print(str.zfill(10))    #000Welcome
print('-100'.zfill(10))  #-000000100
print('+100'.zfill(10))  #+000000100
'5.字符串搜索'
str='awasdhiwhhihuasd~hjdsasdihfi'
print(str.index('asd')) #str中有⼦字符串时回返回收⾃费所在索引值,若不存在则报错
try:
print(str.index('aes'))
except ValueError as v:
print(v)
print(str.find('asd')) #str中有⼦字符串时会返回⾸字母所在索引值,若不存在则返回-1
print(str.find('aes'))
unt('asd')) #返回字符串中包含的⼦串个数
unt('aes')) #不存在则返回0
'6.字符串替换'
str='hello,world!'
place('world','python')) #⽣成替换字符的复制,hello,python!原字符串str未改变
print(str)          #hello,world!
str='awasdhiwhhihuasd~hjdsasdihfi'
place('asd','ASD',2))    #awASDhiwhhihuASD~hjdsasdihfi
'7.字符串添加'
#join() ⽅法⽤于将序列中的元素以指定的字符连接⽣成⼀个新的字符串
#⽤法:str.join(sequence),sequence包括字符串、列表、元祖、集合及字典(字典仅连接key),其中列表、元祖和集合的元素都必须是字符串,否则会报错
lis=['I','am','IronMan!']
print(' '.join(lis)) #I am IronMan!
print('*'.join({'1','2'}))
print('-'.join('ABCD'))
print('+'.join(('a','b','c')))
print('~'.join({'a':1,'b':2}))
'8.字符串修剪'
b="qq-qeasdzxcrtqwe----"
print(b.strip('q')) #-qeasdzxcrtqwe----
'9.字符串切割'
b="this is string example"
print(b.split(' ')) #以空格为分割符进⾏切⽚ ['this', 'is', 'string']
'9.字符串切割'
'''
partition(sep)对给定字符串进⾏切割,切割成三部分
⾸先搜索到字符串sep,将sep之前的部分为⼀部分,sep本⾝作为⼀部分,剩下作为⼀部分partition()与rpartition()之间⼗分相似,主要不同体现在当字符串中没有指定sep时partition()分为三部分,字符串、空⽩、空⽩
rpartition()分为三部分,空⽩、空⽩、字符串'''
test='haoiugdsgfasdhreiuufufg'
print(test.partition('asd')) #('haoiugdsgf', 'asd', 'hreiuufufg')
print(test.partition(' nji'))#('haoiugdsgfasdhreiuufufg', '', '')
print(test.rpartition('njj'))#('', '', 'haoiugdsgfasdhreiuufufg')