平時(shí)使用Python都是處理一些腳本纬霞,其中使用頻率最大的就是字符串的處理方面溉知,因此整理一些常用的字符串處理使用方法圣蝎,學(xué)習(xí)備用。
字符串基本操作
切片
# 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
# 所有的字符串都是直接按照字面的意思來(lái)使用研叫,沒有轉(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)行分隔锤窑,首尾如果有空格,則會(huì)出現(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.count(sub, start= 0,end=len(string))
str = "thing example....wow!!!"
print str.count('i', 0, 5) # 1
print str.count('e') # 2
檢測(cè)字符串中是否包含子字符串
# 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,則替換不超過(guò) 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 符號(hào)('\t')轉(zhuǎn)為空格凳寺,tab 符號(hào)('\t')默認(rèn)的空格數(shù)是 8
檢測(cè)字符串組成
# 檢測(cè)數(shù)字
str.isdigit() # 檢測(cè)字符串是否只由數(shù)字組成
str.isnumeric() # 檢測(cè)字符串是否只由數(shù)字組成,這種方法是只針對(duì)unicode對(duì)象
str.isdecimal() # 檢查字符串是否只包含十進(jìn)制字符。這種方法只存在于unicode對(duì)象
# 檢測(cè)字母
str.isalpha() # 檢測(cè)字符串是否只由字母組成
# 檢測(cè)字母和數(shù)字
str.isalnum() # 檢測(cè)字符串是否由字母和數(shù)字組成
# 檢測(cè)其他
str.isspace() # 檢測(cè)字符串是否只由空格組成
str.islower() # 檢測(cè)字符串是否由小寫字母組成
str.isupper() # 檢測(cè)字符串中所有的字母是否都為大寫
str.istitle() # 檢測(cè)字符串中所有的單詞拼寫首字母是否為大寫彤侍,且其他字母為小寫
字符串處理
str.capitalize() # 將字符串的第一個(gè)字母變成大寫,其他字母變小寫
str.lower() # 轉(zhuǎn)換字符串中所有大寫字符為小寫
str.upper() # 將字符串中的小寫字母轉(zhuǎn)為大寫字母
str.swapcase() # 對(duì)字符串的大小寫字母進(jìn)行轉(zhuǎn)換
max(str) # 返回字符串 str 中最大的字母
min(str) # 返回字符串 str 中最小的字母
len(str) # 返回字符串的長(zhǎng)度
str(arg) # 將 arg 轉(zhuǎn)換為 string
格式化輸出
居中填充
# str.center(width[, fillchar])
# 返回一個(gè)原字符串居中,并使用空格填充至長(zhǎng)度 width 的新字符串肠缨。默認(rèn)填充字符為空格
str = "this is string example....wow!!!"
print str.center(40, 'a') # aaaathis is string example....wow!!!aaaa
靠右填充
# str.zfill(width)
# 返回指定長(zhǎng)度的字符串,原字符串右對(duì)齊盏阶,前面填充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!" % ('Zara', 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