Python基礎(chǔ)之字符串常見操作經(jīng)典實(shí)例詳解
本文實(shí)例講述了Python基礎(chǔ)之字符串常見操作。分享給大家供大家參考,具體如下:
字符串基本操作
切片
# str[beg:end] # (下標(biāo)從 0 開始)從下標(biāo)為beg開始算起,切取到下標(biāo)為 end-1 的元素,切取的區(qū)間為 [beg, end) str = ' python str ' print (str[3:6]) # tho # str[beg:end:step] # 取 [beg, end) 之間的元素,每隔 step 個(gè)取一個(gè) print (str[2:7:2]) # yhn
原始字符串
# 在字符串前加 r/R # 所有的字符串都是直接按照字面的意思來使用,沒有轉(zhuǎn)義特殊或不能打印的字符 print (r'\n') # \n
字符串重復(fù)
# str * n, n * str # n 為一個(gè) int 數(shù)字 str = "hi" print (str*2) # hihi print (2*str) # hihi
in
str = ' python' print ('p' in str) # True print ('py' in str) # True print ('py' not in str) # False
字符串常用函數(shù)
去空格
str = ' python str ' print (str) # 去首尾空格 print (str.strip()) # 去左側(cè)空格 print (str.lstrip()) # 去右側(cè)空格 print (str.rstrip())
分隔字符串
str = ' 1 , 2 , 3 , 4 , 5 , ' # 默認(rèn)使用空格分隔 print (str.split()) # ['1', ',', '2', ',', '3', ',', '4', ',', '5', ','] # 指定使用空格進(jìn)行分隔,首尾如果有空格,則會出現(xiàn)在結(jié)果中 print (str.split(' ')) # ['', '1', ',', '2', ',', '3', ',', '4', ',', '5', ',', ''] # 指定其他字符串進(jìn)行分隔 print (str.split(',')) # [' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' '] print (str.split('3 ,')) # [' 1 , 2 , ', ' 4 , 5 , '] str = 'mississippi' print (str.rstrip('ip')) # 取行, python 中把 "\r","\n","\r\n",作為行分隔符 str = 'ab c\n\nde fg\rkl\r\n' print (str.splitlines()) # ['ab c', '', 'de fg', 'kl'] print (str.splitlines(True)) # ['ab c\n', '\n', 'de fg\r', 'kl\r\n']
拼接字符串
# str.join()方法用于將序列中的元素以指定的字符連接生成一個(gè)新的字符串。 str = '-' seq = ("a", "b", "c"); # 字符串序列 print (str.join(seq)) # 'a-b-c'
統(tǒng)計(jì)字符串里某個(gè)字符出現(xiàn)的次數(shù)
str = "thing example....wow!!!" print (str.count('i', 0, 5)) # 1 print (str.count('e') ) # 2
檢測字符串中是否包含子字符串
# str.find(str, beg=0, end=len(string)) # 如果包含子字符串返回開始的索引值,否則返回-1。 str1 = "this is string example....wow!!!" str2 = "exam" print (str1.find(str2)) # 15 print (str1.find(str2, 10)) # 15 print (str1.find(str2, 40)) # -1 # str.index(str, beg=0, end=len(string)) # 如果包含子字符串返回開始的索引值,否則拋出異常。 print (str1.index(str2)) # 15 print (str1.index(str2, 10)) # 15 print (str1.index(str2, 40)) # Traceback (most recent call last): # File "test.py", line 8, in # print str1.index(str2, 40) # ValueError: substring not found # shell returned 1 # str.rfind(str, beg=0, end=len(string)) # str.rindex(str, beg=0, end=len(string))
判斷字符串是否以指定前綴、后綴結(jié)尾
# str.startswith(str, beg=0,end=len(string)) # 檢查字符串以指定子字符串開頭,如果是則返回 True,否則返回 False str = "this is string example....wow!!!" print (str.startswith( 'this' )) # True print (str.startswith( 'is', 2, 4 )) # True print (str.startswith( 'this', 2, 4 )) # False # str.endswith(suffix[, start[, end]]) # 以指定后綴結(jié)尾返回True,否則返回False suffix = "wow!!!" print (str.endswith(suffix)) # True print (str.endswith(suffix,20)) # True suffix = "is" print (str.endswith(suffix, 2, 4)) # True print (str.endswith(suffix, 2, 6)) # False
根據(jù)指定的分隔符將字符串進(jìn)行分割
# str.partition(del) # 返回一個(gè)3元的元組,第一個(gè)為分隔符左邊的子串,第二個(gè)為分隔符本身,第三個(gè)為分隔符右邊的子串。 str = "http://www.baidu.com/" print (str.partition("://")) # ('http', '://', 'www.baidu.com/') # string.rpartition(str) 從右邊開始
替換字符串
# str.replace(old, new[, max]) # 字符串中的 old(舊字符串) 替換成 new(新字符串),如果指定第三個(gè)參數(shù)max,則替換不超過 max 次。 str = "thing example....wow!!! thisslly string"; print (str.replace("is", "was")) # thwas was string example....wow!!! thwas was really string print (str.replace("is", "was", 3)) # thwas was string example....wow!!! thwas is really string # str.expandtabs(tabsize=8) # 把字符串中的 tab 符號('\t')轉(zhuǎn)為空格,tab 符號('\t')默認(rèn)的空格數(shù)是 8
檢測字符串組成
# 檢測數(shù)字 str.isdigit() # 檢測字符串是否只由數(shù)字組成 str.isnumeric() # 檢測字符串是否只由數(shù)字組成,這種方法是只針對unicode對象 str.isdecimal() # 檢查字符串是否只包含十進(jìn)制字符。這種方法只存在于unicode對象 # 檢測字母 str.isalpha() # 檢測字符串是否只由字母組成 # 檢測字母和數(shù)字 str.isalnum() # 檢測字符串是否由字母和數(shù)字組成 # 檢測其他 str.isspace() # 檢測字符串是否只由空格組成 str.islower() # 檢測字符串是否由小寫字母組成 str.isupper() # 檢測字符串中所有的字母是否都為大寫 str.istitle() # 檢測字符串中所有的單詞拼寫首字母是否為大寫,且其他字母為小寫
字符串處理
str.capitalize() # 將字符串的第一個(gè)字母變成大寫,其他字母變小寫 str.lower() # 轉(zhuǎn)換字符串中所有大寫字符為小寫 str.upper() # 將字符串中的小寫字母轉(zhuǎn)為大寫字母 str.swapcase() # 對字符串的大小寫字母進(jìn)行轉(zhuǎn)換 max(str) # 返回字符串 str 中最大的字母 min(str) # 返回字符串 str 中最小的字母 len(str) # 返回字符串的長度 str(arg) # 將 arg 轉(zhuǎn)換為 string
格式化輸出
居中填充
# str.center(width[, fillchar]) # 返回一個(gè)原字符串居中,并使用空格填充至長度 width 的新字符串。默認(rèn)填充字符為空格 str = "this is string example....wow!!!" print (str.center(40, 'a')) # aaaathis is string example....wow!!!aaaa
靠右填充
# str.zfill(width) # 返回指定長度的字符串,原字符串右對齊,前面填充0 str = "this is string example....wow!!!" print (str.zfill(40)) # 00000000this is string example....wow!!!
輸出格式
print ("My name is %s and weight is %d kg!" % ('Cool', 21)) # My name is Zara and weight is 21 kg! print ('%(language)s has %(number)03d quote types.' % {"language": "Python", "number": 2}) # Python has 002 quote types. # str.format(*args, **kwargs) print ('{0}, {1}, {2}'.format('a', 'b', 'c')) # a, b, c print ('{1}, {0}, {2}'.format('a', 'b', 'c')) # b, a, c
更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python字符串操作技巧匯總》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python列表(list)操作技巧總結(jié)》、《Python編碼操作技巧總結(jié)》、《Python函數(shù)使用技巧總結(jié)》及《Python入門與進(jìn)階經(jīng)典教程》
希望本文所述對大家Python程序設(shè)計(jì)有所幫助。
- Python基礎(chǔ)之文本常量與字符串模板
- Python基礎(chǔ)之字符串格式化詳解
- Python入門基礎(chǔ)之?dāng)?shù)字字符串與列表
- Python基礎(chǔ)學(xué)習(xí)之基本數(shù)據(jù)結(jié)構(gòu)詳解【數(shù)字、字符串、列表、元組、集合、字典】
- Python 基礎(chǔ)之字符串string詳解及實(shí)例
- Python 專題三 字符串的基礎(chǔ)知識
- Python 基礎(chǔ)知識之字符串處理
- Python中關(guān)于字符串對象的一些基礎(chǔ)知識
- Python 中的字符串基礎(chǔ)與應(yīng)用小結(jié)
相關(guān)文章
TensorFlow dataset.shuffle、batch、repeat的使用詳解
今天小編就為大家分享一篇TensorFlow dataset.shuffle、batch、repeat的使用詳解,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-01-01TensorFlow實(shí)現(xiàn)Softmax回歸模型
這篇文章主要介紹了TensorFlow實(shí)現(xiàn)Softmax回歸模型,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-03-03Python selenium模擬網(wǎng)頁點(diǎn)擊爬蟲交管12123違章數(shù)據(jù)
本次介紹怎么以模擬點(diǎn)擊方式進(jìn)入交管12123爬取車輛違章數(shù)據(jù),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-05-05mac下pycharm設(shè)置python版本的圖文教程
今天小編就為大家分享一篇mac下pycharm設(shè)置python版本的圖文教程,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-06-06解讀opencv->tensorrt的數(shù)據(jù)排列方式
這篇文章主要介紹了解讀opencv->tensorrt的數(shù)據(jù)排列方式,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-02-02