Python基礎之字串常見操作經典例項詳解
阿新 • • 發佈:2020-02-26
本文例項講述了Python基礎之字串常見操作。分享給大家供大家參考,具體如下:
字串基本操作
切片
# str[beg:end] # (下標從 0 開始)從下標為beg開始算起,切取到下標為 end-1 的元素,切取的區間為 [beg,end) str = ' python str ' print (str[3:6]) # tho # str[beg:end:step] # 取 [beg,end) 之間的元素,每隔 step 個取一個 print (str[2:7:2]) # yhn
原始字串
# 在字串前加 r/R # 所有的字串都是直接按照字面的意思來使用,沒有轉義特殊或不能列印的字元 print (r'\n') # \n
字串重複
# str * n,n * str # n 為一個 int 數字 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
字串常用函式
去空格
str = ' python str ' print (str) # 去首尾空格 print (str.strip()) # 去左側空格 print (str.lstrip()) # 去右側空格 print (str.rstrip())
分隔字串
str = ' 1,2,3,4,5,' # 預設使用空格分隔 print (str.split()) # ['1',','2','3','4','5','] # 指定使用空格進行分隔,首尾如果有空格,則會出現在結果中 print (str.split(' ')) # ['','1',''] # 指定其他字串進行分隔 print (str.split(',')) # [' 1 ',' 2 ',' 3 ',' 4 ',' 5 ',' '] print (str.split('3,')) # [' 1,' 4,'] 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()方法用於將序列中的元素以指定的字元連線生成一個新的字串。 str = '-' seq = ("a","b","c"); # 字串序列 print (str.join(seq)) # 'a-b-c'
統計字串裡某個字元出現的次數
str = "thing example....wow!!!" print (str.count('i',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,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,end=len(string)) # str.rindex(str,end=len(string))
判斷字串是否以指定字首、字尾結尾
# str.startswith(str,end=len(string)) # 檢查字串以指定子字串開頭,如果是則返回 True,否則返回 False str = "this is string example....wow!!!" print (str.startswith( 'this' )) # True print (str.startswith( 'is',4 )) # True print (str.startswith( 'this',4 )) # False # str.endswith(suffix[,start[,end]]) # 以指定字尾結尾返回True,否則返回False suffix = "wow!!!" print (str.endswith(suffix)) # True print (str.endswith(suffix,20)) # True suffix = "is" print (str.endswith(suffix,4)) # True print (str.endswith(suffix,6)) # False
根據指定的分隔符將字串進行分割
# str.partition(del) # 返回一個3元的元組,第一個為分隔符左邊的子串,第二個為分隔符本身,第三個為分隔符右邊的子串。 str = "http://www.baidu.com/" print (str.partition("://")) # ('http','://','www.baidu.com/') # string.rpartition(str) 從右邊開始
替換字串
# str.replace(old,new[,max]) # 字串中的 old(舊字串) 替換成 new(新字串),如果指定第三個引數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')轉為空格,tab 符號('\t')預設的空格數是 8
檢測字串組成
# 檢測數字 str.isdigit() # 檢測字串是否只由數字組成 str.isnumeric() # 檢測字串是否只由數字組成,這種方法是隻針對unicode物件 str.isdecimal() # 檢查字串是否只包含十進位制字元。這種方法只存在於unicode物件 # 檢測字母 str.isalpha() # 檢測字串是否只由字母組成 # 檢測字母和數字 str.isalnum() # 檢測字串是否由字母和數字組成 # 檢測其他 str.isspace() # 檢測字串是否只由空格組成 str.islower() # 檢測字串是否由小寫字母組成 str.isupper() # 檢測字串中所有的字母是否都為大寫 str.istitle() # 檢測字串中所有的單詞拼寫首字母是否為大寫,且其他字母為小寫
字串處理
str.capitalize() # 將字串的第一個字母變成大寫,其他字母變小寫 str.lower() # 轉換字串中所有大寫字元為小寫 str.upper() # 將字串中的小寫字母轉為大寫字母 str.swapcase() # 對字串的大小寫字母進行轉換 max(str) # 返回字串 str 中最大的字母 min(str) # 返回字串 str 中最小的字母 len(str) # 返回字串的長度 str(arg) # 將 arg 轉換為 string
格式化輸出
居中填充
# str.center(width[,fillchar]) # 返回一個原字串居中,並使用空格填充至長度 width 的新字串。預設填充字元為空格 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},'c')) # b,a,c
更多關於Python相關內容感興趣的讀者可檢視本站專題:《Python字串操作技巧彙總》、《Python資料結構與演算法教程》、《Python列表(list)操作技巧總結》、《Python編碼操作技巧總結》、《Python函式使用技巧總結》及《Python入門與進階經典教程》
希望本文所述對大家Python程式設計有所幫助。