Python基礎之字符串常見操作經典實例詳解
本文實例講述了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) # hihiprint (2*str) # hihiin
str = ’ python’print (’p’ in str) # Trueprint (’py’ in str) # Trueprint (’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’, ’,’, ’2’, ’,’, ’3’, ’,’, ’4’, ’,’, ’5’, ’,’, ’’]# 指定其他字符串進行分隔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','rn',作為行分隔符str = ’ab cnnde fgrklrn’print (str.splitlines()) # [’ab c’, ’’, ’de fg’, ’kl’]print (str.splitlines(True)) # [’ab cn’, ’n’, ’de fgr’, ’klrn’] 拼接字符串
# str.join()方法用于將序列中的元素以指定的字符連接生成一個新的字符串。str = ’-’seq = ('a', 'b', 'c'); # 字符串序列print (str.join(seq)) # ’a-b-c’統計字符串里某個字符出現的次數
str = 'thing example....wow!!!'print (str.count(’i’, 0, 5)) # 1print (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)) # 15print (str1.find(str2, 10)) # 15print (str1.find(str2, 40)) # -1# str.index(str, beg=0, end=len(string))# 如果包含子字符串返回開始的索引值,否則拋出異常。print (str1.index(str2)) # 15print (str1.index(str2, 10)) # 15print (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))判斷字符串是否以指定前綴、后綴結尾
# str.startswith(str, beg=0,end=len(string))# 檢查字符串以指定子字符串開頭,如果是則返回 True,否則返回 Falsestr = 'this is string example....wow!!!'print (str.startswith( ’this’ )) # Trueprint (str.startswith( ’is’, 2, 4 )) # Trueprint (str.startswith( ’this’, 2, 4 )) # False# str.endswith(suffix[, start[, end]])# 以指定后綴結尾返回True,否則返回Falsesuffix = 'wow!!!'print (str.endswith(suffix)) # Trueprint (str.endswith(suffix,20)) # Truesuffix = 'is'print (str.endswith(suffix, 2, 4)) # Trueprint (str.endswith(suffix, 2, 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 stringprint (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)# 返回指定長度的字符串,原字符串右對齊,前面填充0str = '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, cprint (’{1}, {0}, {2}’.format(’a’, ’b’, ’c’)) # b, a, c
更多關于Python相關內容感興趣的讀者可查看本站專題:《Python字符串操作技巧匯總》、《Python數據結構與算法教程》、《Python列表(list)操作技巧總結》、《Python編碼操作技巧總結》、《Python函數使用技巧總結》及《Python入門與進階經典教程》
希望本文所述對大家Python程序設計有所幫助。
相關文章: