Python字符串常用方法以及其應(yīng)用場景詳解
前言
字符串作為一種重要的Python基本數(shù)據(jù)類型,在數(shù)據(jù)處理中發(fā)揮著不可或缺的作用,如果對它的方法能夠靈活使用,能夠達(dá)到事半功倍的效果。下面我們選取一些常用的方法,簡述其應(yīng)用場景。
一、最大化最小化方法
字符串的最大化方法upper()和最小化方法lower()可以將字符串全部轉(zhuǎn)換為大寫和小寫。在數(shù)據(jù)處理分析過程中,如果涉及到字符串的比較和統(tǒng)計,尤其涉及到英文的,一般需要將字符串全部轉(zhuǎn)化小寫再進(jìn)行比較統(tǒng)計,否則可能會不準(zhǔn)。
比如根據(jù)用戶的輸入,決定接下來的程序是否執(zhí)行,如果用戶輸入n則不執(zhí)行,為了讓程序設(shè)計的更加友好,需要考慮用戶可能輸入N的情況,該問題可以通過lower()或者upper()來解決。
>>> choice = input('是否繼續(xù)執(zhí)行程序,輸入n或N則結(jié)束:')
是否繼續(xù)執(zhí)行程序,輸入n或N則結(jié)束:N
>>> if choice == 'n'or choice == 'N': # 常規(guī)處理方式
print('程序結(jié)束')
>>> if choice.lower() == 'n': # 推薦用該方法處理
print('程序結(jié)束')比如現(xiàn)在通過分詞工具,已經(jīng)把一段英文分詞單詞的列表,現(xiàn)在要統(tǒng)計“when”出現(xiàn)的次數(shù),一般需要再統(tǒng)計之前將字符串全部最小化下。
>>> words = ['When', 'you', 'fall', 'stand', 'up.', 'And', 'when', 'you', 'break', 'stand', 'tough', 'And', 'when', 'they', 'say', 'you', 'can't,', 'you', 'say', 'I', 'can', 'I', 'can']
>>> count = 0
>>> sta_word = 'when'
>>> for word in words:
if word.lower() == sta_word:
count += 1
>>> print('{}出現(xiàn)了{(lán)}次'.format('when', count))
when出現(xiàn)了3次二、統(tǒng)計次數(shù)方法
統(tǒng)計次數(shù)的count()方法可以快速統(tǒng)計字符串中某個子串出現(xiàn)的次數(shù),但這個方法在列表數(shù)據(jù)類型中應(yīng)用較多,在字符串中應(yīng)用很少,使用不當(dāng)容易造成不易察覺的錯誤。
比如統(tǒng)計“帽子和服裝如何搭配才好看”這句話中“和服”出現(xiàn)的次數(shù),雖然出現(xiàn)了“和服”,但不是想要統(tǒng)計的結(jié)果,對于英文中很多單詞有多種時態(tài),更是如此。對于文本中詞頻的統(tǒng)計,一般需要先進(jìn)行分詞處理,英文可能還需要進(jìn)行詞形還原處理,然后再統(tǒng)計詞頻。
>>> "帽子和服裝如何搭配才好看".count("和服")
1
>>> import jieba
>>> words = jieba.lcut("帽子和服裝如何搭配才好看")
>>> words
['帽子','和','服裝','如何','搭配','才','好看']
>>> words.count("和服") # 分詞后再統(tǒng)計
0三、去掉左右側(cè)字符方法
在做文本處理任務(wù)時,對于網(wǎng)絡(luò)上爬取或者其他渠道獲取的數(shù)據(jù)信息,經(jīng)常會存在“噪聲”,即會有一些沒有實際意義的字符,干擾文本的格式和信息的提取,此時strip()、lstrip()、rstrip()方法就可以幫助刪除掉字符串頭部和尾部的指定字符。當(dāng)字符沒有被指定時,默認(rèn)去除空格或換行符。lstrip()代表刪除字符串左側(cè)(即頭部)出現(xiàn)的指定字符,rstrip()代表刪除字符串右側(cè)(即尾部)出現(xiàn)的指定字符。下面通過幾個例子來說明。
>>> temp_str = " tomorrow is another day "
>>> temp_str.strip()
'tomorrow is another day'
>>> temp_str = "# tomorrow is another day @"
>>> temp_str.strip('#')
' tomorrow is another day @'
>>> temp_str.strip('# @')
'tomorrow is another day'
>>> temp_str = "#@ tomorrow is another day @"
>>> temp_str.lstrip('@# ')
'tomorrow is another day @'四、字符串分隔方法
當(dāng)字符串具有特定的格式,或者需要處理的數(shù)據(jù)具有結(jié)構(gòu)化特點,比如excel表格的數(shù)據(jù)、或者json格式的文件等,當(dāng)提取其中的某一個或幾個字段時,需要先對字符串進(jìn)行分隔。split()方法以指定的分隔符為基準(zhǔn),將分隔后得到的字符串以數(shù)組類型返回,方便進(jìn)行之后的操作。當(dāng)沒有指定分隔符時,默認(rèn)以空格分隔。
>>> temp_str = "Whatever is worth doing is worth doing well"
>>> temp_str.split()
['Whatever', 'is', 'worth', 'doing', 'is', 'worth', 'doing', 'well']
>>> temp_str = "tomorrow#is#another#day"
>>> temp_str.split('#')
['tomorrow', 'is', 'another', 'day']
>>> temp_str = ‘"name":"Mike","age":18,"sex":"male","hair":"black"'
>>> temp_str.split(',')
['"name":"Mike"', '"age":18', '"sex":"male"', '"hair":"black"']五、字符串替換方法
字符串替換也是很常用的方法之一。例如發(fā)現(xiàn)有輸入錯誤的時候,正確的要替換掉錯誤的,或者需要將一些沒有意義的字符統(tǒng)一去除或者換成空格的時候,都可以考慮使用replace()方法。第三個參數(shù)為可選參數(shù),表示替換的最大次數(shù)。
>>> temp_str = "this is really interesting, and that is boring."
>>> temp_str.replace('is','was')
'thwas was really interesting, and that was boring.'
>>> temp_str.replace('is','was')
'this was really interesting, and that was boring.'
>>> temp_str = 'I really really really like you.'
>>> temp_str.replace("really","",2)
'I really like you.'上例顯示出,字符串中出現(xiàn)的所有is都被進(jìn)行了替換,包括包含is的單詞,這也是編程中需要考慮的問題。如果是英文字符串,可以考慮通過加上空格的方式來避免錯誤的替換,如第四行所示。
六、字符串拼接方法
字符串的拼接方法與其分隔方法可以看作是互逆操作,join()方法將序列中的元素以指定的字符連接,生成一個新的字符串。這個序列可以是字符串、元組、列表、字典等。
>>> seq = 'hello world'
>>> ":".join(seq)
'h:e:l:l:o: :w:o:r:l:d'
>>> seq = ('Whatever', 'is', 'worth', 'doing', 'is', 'worth', 'doing', 'well')
>>> "*".join(seq)
'Whatever*is*worth*doing*is*worth*doing*well'
>>> seq = ['Whatever', 'is', 'worth', 'doing', 'is', 'worth', 'doing', 'well']
>>> " ".join(seq)
'Whatever is worth doing is worth doing well'
>>> seq = ['"name":"Mike"', '"age":18', '"sex":"male"', '"hair":"black"']
>>> "#".join(seq)
'"name":"Mike"#"age":18#"sex":"male"#"hair":"black"'七、判斷是否為數(shù)字的方法
isdigit()方法用于判斷一個字符串是否全部都由數(shù)字組成,返回值為布爾值。如果字符串中存在小數(shù)點或者符號,也不能認(rèn)為全都是數(shù)字,如下例所示:
>>> num = "13579" >>> num.isdigit() True >>> num = '1.0' >>> num.isdigit() False >>> num = '-1' >>> num.isdigit() False
八、判斷是否為空格的方法
isspace()方法用于判斷一個字符串是否全部都由空格組成,返回值為布爾值。要注意的是,空字符串返回False。如下例所示:
>>> t = '' >>> t.isspace() False >>> t = ' ' >>> t.isspace() True
九、判斷前綴和后綴的方法
startswith()和endswith()分別用于判斷字符串的前綴和后綴,即它的開始部分和結(jié)尾部分,返回值為布爾值,后面有兩個可選參數(shù),相當(dāng)于對字符串做一個切片后再判斷前綴/后綴。如下例所示:
>>> temp_str = "Whatever is worth doing is worth doing well"
>>> temp_str.startswith("W")
True
>>> temp_str.startswith("What")
True
>>> temp_str.startswith('Whatever',2)
False
>>> temp_str.endswith("well",2)
True
>>> temp_str.endswith("we",2,-2)
True補充:更多Python字符串常用方法
a = "hello world"
# 字符串不能通過索引進(jìn)行修改 name[0] = 'q'
# 切片,查找字符串當(dāng)中的一段值,[起始值:終止值:步長]不寫步長默認(rèn)是1
print(a[0:5:])
print(a[::-1]) # 步長負(fù)數(shù)倒過來走,不寫起始值和終止值就走完全部
print(a[::1])
print(len(a)) # len方法獲取字符串的長度
# in 和 not in :判斷一個字符串是否在一個大的字符串中
# 返回值為布爾類型
print('hello' in 'hello world')
print('nihao' not in 'hello world')
# 字符串的增
print('nihao', 'Python')
print('nihao' + 'Python')
# format 前面的大括號寫上數(shù)字代表著取后面括號里的索引位置
print('==============format================')
print('my name is {}'.format(100))
print('my name is {1},my age is {0}'.format('dayv', 18))
print('my name is {0},my age is {1}'.format('dayv', 18))
# join 把列表里的元素組成字符串
str1 = '真正的勇士'
str2 = '敢于直面慘淡的人生'
str3 = '敢于正視淋漓的鮮血'
print(''.join([str1, str2, str3]))
# 前面的逗號表示用什么來隔開,列表中只能是字符串才能使用join方法
print(','.join([str1, str2, str3]))
# 刪 del
name1 = 'nihao'
del name1 # 這就把這個變量刪除了,在輸出這個變量就會出錯
# 改
# 字符串變大小寫 upper , lower ,
name1 = 'abc'
print('大寫:' + name1.upper())
print(name1.lower())
# capitalize 將第一個字母轉(zhuǎn)換成大寫
print(name1.capitalize())
# 將每個單詞的首字母大寫 title
name2 = 'hello world'
print('每個單詞首字母大寫:' + name2.title())
print('原name2的值' + name2)
# 將字符串切分成列表 默認(rèn)空格為字符切分 split
name1 = 'a b cd e'
print(name1.split())
# 括號里寫什么就用什么切分 !!!!!!!!!!!!!!!!!!!!
name1 = 'a1b1cd1e'
print("自己配置用什么東西切分", name1.split('1')) # 返回的是列表
# rsplit('指定用什么切片', 切幾次),反過來切
print('切片倒過來切使用rsplit', name1.rsplit('1', 1)) # 倒過來切一個元素
# 替換replace(被替換的字符,替換的字符,個數(shù)) !!!!!!!!!!!!!!
print(name1.replace('1', '0'))
print(name1.replace('1', '0', 1)) # 個數(shù)是從左往右的順序替換
aaaaa = ' sdf kkf k k '
print('使用替換去除字符串中的全部空格', aaaaa.replace(" ", ''))
# strip 除去字符串兩邊的空格,中間的不會管
name1 = ' ni h ao '
print(name1.strip())
# 查
# find index
# 查找字符串在大字符串的那個索引位置(起始索引)
name1 = 'PythonPythonPython'
print("使用find查找的索引位置", name1.find('on'))
# 找不到會返回-1
print("使用index查找的索引位置:", name1.index('on'))
# index方法找不到會報錯
# count 統(tǒng)計一個字符串在大字符串里面出現(xiàn)的次數(shù)
print(name1.count('qi'))
# 判斷一個字符串里的數(shù)據(jù)是不是都是數(shù)字 isdigit 返回布爾值
num = '156465'
print(num.isdigit())
# 判斷一個字符串里的數(shù)據(jù)是不是都是字母 isalpha
num = 'ksdjflks'
print(num.isalpha())
# 比較后面一個元素是否是前面一個元素的開頭,startswith
# 比較后面一個元素是否是前面一個元素的結(jié)尾 endswith
mm = 'Python nihao'
print(mm.startswith('Pyth'))
print(mm.endswith('Pytho'))
# 判斷字符串是否全是大寫isupper 是否全是小寫islower
# 轉(zhuǎn)義字符 \n換行 \t
print('hello \nworld')
print('z\tiyu')
print('Pyth \t on')
print('Python123')
# 反轉(zhuǎn)義
print(r'zhai \t dada') # 加r
print('zhai \\t dada') # 或者寫兩個斜杠
# 控制字符串的輸入字?jǐn)?shù)
print('123456'[:5]) # 只會輸入前五個數(shù)總結(jié)
到此這篇關(guān)于Python字符串常用方法以及其應(yīng)用場景的文章就介紹到這了,更多相關(guān)Python字符串常用方法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
解決Python 中JSONDecodeError: Expecting value:&n
這篇文章主要介紹了解決Python 中JSONDecodeError: Expecting value: line 1 column 1 (char 0)錯誤問題,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-03-03
利用For循環(huán)遍歷Python字典的三種方法實例
字典由多個鍵和其對應(yīng)的值構(gòu)成的鍵—值對組成,鍵和值中間以冒號:隔開,項之間用逗號隔開,整個字典是由大括號{}括起來的,下面這篇文章主要給大家介紹了關(guān)于如何利用For循環(huán)遍歷Python字典的三種方法,需要的朋友可以參考下2022-03-03
解決Python報錯:ValueError:operands?could?not?be?broadcast?t
這篇文章主要給大家介紹了關(guān)于解決Python報錯:ValueError:operands?could?not?be?broadcast?together?with?shapes的相關(guān)資料,文中通過實例代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-02-02

