字符串相關操作大致總結以下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'
print(str.center(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'))
print(str.count('asd')) #返回字符串中包含的子串個數
print(str.count('aes')) #不存在則返回0
'6.字符串替換'
str='hello,world!'
print(str.replace('world','python')) #生成替換字符的復制,hello,python!原字符串str未改變
print(str) #hello,world!
str='awasdhiwhhihuasd~hjdsasdihfi'
print(str.replace('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')