Python3內置字符串方法詳解


官網文檔地址:https://docs.python.org/3/library/stdtypes.html#string-methods
基於 Python 3.X 版本

str.capitalize() --> String   返回字符串,其首字母大寫,其余部分小寫

1>>> str = "TEST"
2>>> str1= "test"
3>>> print(str + "-->" + str.capitalize() +'\n' + "-->" + str + str1.capitalize()) 4 TEST-->Test 5 TEST-->Test

str.casefold() --> String   字符串轉換成小寫,用於不區分大小寫的字符串比較

1>>> str = "TESTtest"
2>>> print(str.casefold()) 3 testtest

str.center(width[, fillchar]) -->String   指定長度(此處是長度並不是索引值)填充字符

1>>> str = "Python"
2>>> print(str.center(7,'t')) 3>>> print(str.center(8,'8')) 4>>> print(str.center(9,'9')) 5>>> print(str.center(10,'X'))# 6 tPython 7 8Python8 8 99Python9 9 XXPythonXX

str.count(sub[, start[, end]]) --> int     查找某字符串(sub)出現的次數 ,也可以查找在某個位置范圍 [2,6] 內出現子字符串的次數 

1 >>>str = "Pythont"
2 >>>sub = "t"
3 >>>print(str.count(sub))#查找‘t’在“Pythont”中出現的次數
4 2
5 >>>print(str.count(sub,2,6))#在[2,6]范圍 內出現的次數
6 1

 str.encode(encoding="utf-8", errors="strict") --> Object    以指定的編碼格式解碼字符串。默認編碼為字符串編碼(適合python2中處理中文)

1>>> str = "中文"
2>>> sub = "test"
3>>> print(str.encode(encoding='utf_8', errors='strict')) 4 b'\xe4\xb8\xad\xe6\x96\x87'
5>>> print(sub.encode(encoding='utf_8', errors='strict')) 6 b'test'

 str.endswith(suffix[, start[, end]])  --> Bool(True or False)    用於判斷字符串是否以指定后綴結尾,如果以指定后綴結尾返回True,否則返回False。

可選參數"start"與"end"為檢索字符串的開始與結束位置

1>>> str = "TestPython"
2>>> sub = "test"
3>>> print(str.endswith('on'))# 判斷該字符串以指定后綴‘on’結尾 4 True 5>>> print(str.endswith("t",4,7))#判斷4位置以‘t’開始,7位置以‘t’結尾 6 True 7>>> print(str.endswith("t",4,9)) 8 False

 str.expandtabs(tabsize=8) --> String    將字符串中的tab符號('\t')轉換為空格,默認的空格數是8;tabsize -- 指定轉換字符串中的 tab 符號('\t')轉為空格的字符數。

1 >>> '01\t012\t0123\t01234'.expandtabs() 2 '01 012 0123 01234'
3 >>> '01\t012\t0123\t01234'.expandtabs(4) 4 '01 012 0123 01234'

 

 str.find(sub[, start[, end]]) --> int   檢測字符串中是否包含子字符串,如果指定 beg(開始)和 end(結束)范圍,則檢查是否包含在指定范圍內,如果包含子字符串,則返回開始的索引值(下標,從0開始),否則返回-1。
 str.rfind(sub[, start[, end]]) --> int        返回字符串最后一次出現的位置,如果沒有匹配項則返回-1。

1 >>> str = "TestPython"
2 >>> sub = "Test"
3 >>> print(str.find(sub))#檢測是否包含子字符串sub,如果包含則返回開始的索引值,否則返回-1
4 0 5 >>> print(str.find('P')) 6 4
7 >>> print(str.find('A')) 8 -1

  >>> s = 'lilin is good li lao ban'
  >>> s.rfind('li')
  14
  >>> s.rfind('li',0,8)
  2

 

 注意:只有當你知道子字符串的位置時才是用find()方法。如果你需要檢測子字符串是否包含,請至少用 in 運算符:

1 >>> 'Py' in 'Python'
2 True

 

 str.format(*args, **kwargs) --> String     格式換字符串輸出(方法與%相似,但可以指定順序) 仔細閱讀下面的例子

1 >>> str = "programmer"
2 >>> sub = "Python"
3 >>> print('I am a {}, and learn {}'.format(str,sub)) 4 I am a programmer, and learn Python 5 >>> print('I am a {1}, and learn {0}'.format(str,sub)) 6 I am a Python, and learn programmer 7 >>> print('I am a {name}, and learn {tool}'.format(name = str,tool = sub)) 8 I am a programmer, and learn Python

 str.format_map(mapping)  --> String     執行字符串格式化操作,替換字段使用{}分隔,同str.format(**mapping), 除了直接使用mapping,而不復制到一個dict

1 >>> name = "Peter"
2 >>> country = "China"
3 >>> print('I\'m {name} and bron in {country}.'.format_map(vars())) 4 I'm Peter and bron in China.
5 
6 >>> str = "programmer"
7 >>> sub = "Python"
8 >>> print('I am a {str}, and learnning {sub}.'.format_map(vars())) 9 I am a programmer, and learn Python.

注: 此方法 出於 Python 3.2 之后

str.index(sub[, start[, end]]) --> int     檢測字符串string中是否包含子字符串 sub,如果存在,則返回sub在string中的索引值(下標),如果指定began(開始)和 end(結束)范圍,則檢查是否包含在指定范圍內,該方法與 python find()方法一樣,只不過如果str不在 string中會報一個異常(ValueError: substring not found)

>>> str = "programmer"
>>> print(str.index('m')) 6
>>> print(str.index('m',6,9)) 6
>>> print(str.index('m',7,9)) 7

 

 

字符串條件判斷:

str.isalnum() --> Bool (True or False)    判斷字符串String是否由字符串或數字組成,並且至少有一個字符(不為空)簡而言之:只要 c.isalpha()c.isdecimal()c.isdigit()c.isnumeric() 中任意一個為真,則 c.isalnum() 為真。

'dobi'.isalnum() # True
'dobi123'.isalnum() # True
'123'.isalnum() # True
''.isalnum() # True
'dobi_123'.isalnum() # False
'dobi 123'.isalnum() # False
'%'.isalnum() # False

str.isalpha() -->Bool (True or False)     判斷字符串String是否只由字母組成,並且至少有一個字符(不為空)

'dobi'.isalpha() # True
'do bi'.isalpha() # False
'dobi123'.isalpha() # False
''.isalpha() # True

str.isdecimal()小數; str.isdigit()數字; str.isnumeric()數值 -->Bool (True or False)     判斷字符串String是否只由小數/數字/數值組成,並且至少有一個字符(不為空)
三個方法的區別在於對 Unicode 通用標識的真值判斷范圍不同:
isdecimal: Nd,   (小數)  all decimals are digits, but not all digits are decimals(所有小數都是數字,但不是全部數字都是小數)
isdigit: No, Nd,  (數字)
isnumeric: No, Nd, Nl  (數值)
digit 與 decimal 的區別在於有些數值字符串,是 digit 卻非 decimal ,具體戳 這里

num = '\u2155'
print(num) #
num.isdecimal(), num.isdigit(), num.isnumeric() # (False, False, True)
num = '\u00B2'
print(num) # ²
num.isdecimal(), num.isdigit(), num.isnumeric() # (False, True, True)
num = "1"  #unicode
num.isdecimal(), num.isdigit(), num.isnumeric() # (Ture, True, True)
num = "'Ⅶ'" num.isdecimal(), num.isdigit(), num.isnumeric() # (False, False, True)
num = "" num.isdecimal(), num.isdigit(), num.isnumeric() # (False, False, True)
num = b"1" # byte
num.isdigit()   # True
num.isdecimal() # AttributeError 'bytes' object has no attribute 'isdecimal'
num.isnumeric() # AttributeError 'bytes' object has no attribute 'isnumeric'

str.isidentifier() -->Bool (True or False)    判斷字符串中是否是有效標識符

'def'.isidentifier() # True
'with'.isidentifier() # True
'false'.isidentifier() # True
'dobi_123'.isidentifier() # True
'dobi 123'.isidentifier() # False
'123'.isidentifier() # False

 

str.islower(-->Bool (True or False)    判斷字符串中是否是有效標識符

str = "programmer" sub = "PYTHON"
print(str.islower()) # True
print(sub.islower()) # False
'ß'.islower()   #德語大寫字母 # False

 

 str.isprintable() -->Bool (True or False)    判斷字符串的所有字符都是可打印字符或字符串為空。Unicode 字符集中 “Other” “Separator” 類別的字符為不可打印的字符(但不包括 ASCII 的空格(0x20))。

'dobi123'.isprintable() # True 'dobi123\n'.isprintable() Out[24]: False 'dobi 123'.isprintable() # True 'dobi.123'.isprintable() # True ''.isprintable() # True

 

str.isspace()  -->Bool (True or False)    檢測字符串是否只由空格組成,並且至少有一個字符(判斷字符串中是否至少有一個字符,並且所有字符都是空白字符。)

'\r\n\t'.isspace() #True ''.isspace() #False ' '.isspace() #True

str.istitle() -->Bool (True or False)     判斷字符串中的字符是否是首字母大寫,且其他字母為小寫,其會忽視非字母字符

'How Python Works'.istitle() # True 'How Python WORKS'.istitle() # False 'how python works'.istitle() # False 'How Python Works'.istitle() # True ' '.istitle() # False ''.istitle() # False 'A'.istitle() # True 'a'.istitle() # False '甩甩Abc Def 123'.istitle() # True

str.isupper()  -->Bool (True or False)    檢測字符串中所有的字母是否都為大寫

''.isupper() # False 'DOBI'.isupper() Out[41]: True 'Dobi'.isupper() # False 'DOBI123'.isupper() # True 'DOBI 123'.isupper() # True 'DOBI\t 123'.isupper() # True 'DOBI_123'.isupper() # True '_123'.isupper() # False

 

 

字符串的聯合與分割:

str.join(iterable)       --> String     用指定的字符串,連接元素為字符串的可迭代對象。

'-'.join(['2012', '3', '12']) # '2012-3-12' '-'.join([2012, 3, 12]) # TypeError: sequence item 0: expected str instance, int found '-'.join(['2012', '3', b'12']) #bytes 為非字符串 # TypeError: sequence item 2: expected str instance, bytes found '-'.join(['2012']) # '2012' '-'.join([]) # '' '-'.join([None]) # TypeError: sequence item 0: expected str instance, NoneType found '-'.join(['']) # '' ','.join({'dobi':'dog', 'polly':'bird'}) # 'dobi,polly' ','.join({'dobi':'dog', 'polly':'bird'}.values()) # 'dog,bird'

 

 

str.ljust(width[, fillchar]);  str.rjust(width[, fillchar])

返回指定長度的字符串,字符串內容居左(右)如果長度小於字符串長度,則返回原始字符串,默認填充為 ASCII 空格,可指定填充的字符串。

 width -- 指定填充指定字符后新字符串的總長度.

 fillchar– 要填充的字符,默認為空格。

print('dobi'.ljust(10)) # 'dobi ' print('dobi'.ljust(10, '*')) # 'dobi~~~~~~' print('dobi'.ljust(3, '~')) # 'dobi' print('dobi'.ljust(3)) # 'dobi' print('dobi'.rjust(10)) #' dobi' print('dobi'.rjust(10,'@')) #'@@@@@@dobi' print('dobi'.rjust(3,'@')) #'dobi' print('dobi'.rjust(3)) #'dobi'

 

str.lower() -->String     字符串轉換成小寫    其僅對 ASCII 編碼的字母有效。

print('PYTHON'.lower()) #'python'
print('Python'.lower()) #'python'
print('ß'.lower()) # 'ß' 為德語小寫字母,其有另一種小寫 'ss', lower 方法無法轉換 #'ß'
print('張PYTHON'.lower()) #'張python'

 

str.lstrip([chars]);    str.rstrip([chars]);    str.strip([chars])   -->  string or unicode

去掉(刪除)字符串后面 / 前面/ 兩邊 的空格(默認是空格),或參數中的字符

print(' Python '.lstrip()) #'Python '
print('Test Python lstrip'.lstrip('Test'))#去掉前面的參數中的字符'Test' #' Python lstrip'
print(' Python '.rstrip()) #' Python'
print(' Python '.strip()) #'Python'

static str.maketrans(x[, y[, z]])    str.translate(table)

maktrans 是一個靜態方法,用於生成一個對照表,以供 translate 使用。
如果 maktrans 僅一個參數,則該參數必須是一個字典,字典的 key 要么是一個 Unicode 編碼(一個整數),要么是一個長度為 1 的字符串,字典的 value 則可以是任意字符串、None或者 Unicode 編碼。

#注釋:ord() 函數是 chr() 函數(對於8位的ASCII字符串)或 unichr() 函數(對於Unicode對象)的配對函數,
#它以一個字符(長度為1的字符串)作為參數,返回對應的 ASCII 數值,
#或者 Unicode 數值,如果所給的 Unicode 字符超出了你的 Python 定義范圍,則會引發一個 TypeError 的異常。

a = 'dobi'
ord('o')
# 111
ord('a')
# 97
hex(ord('狗'))
# '0x72d7'
b = {'d':'dobi', 111:' is ', 'b':97, 'i':' \u72d7\u72d7'}
table = str.maketrans(b)
print(a.translate(table))

如果 maktrans 有兩個參數,則兩個參數形成映射,且兩個字符串必須是長度相等;如果有第三個參數,則第三個參數也必須是字符串,該字符串將自動映射到 None

a = 'dobi is a dog' table = str.maketrans('dobi', 'alph') a.translate(table) # 'alph hs a alg'
table = str.maketrans('dobi', 'alph', 'o') a.translate(table) # 'aph hs a ag'

這里插一嘴:Python2.x和3.x下maketrans與translate函數使用上的不同

看一個簡單的例子來說明字符串轉換的過程:
    2.X下的演示過程:

>>> import string                     #導入string模塊
>>> map = string.maketrans('123', 'abc') #建立映射表,將字符串中含有的'1','2','3'替換為'a','b','c'
>>> s = '54321123789'                #轉換前的字符串
>>> s.translate(map)                  #用創建的映射表map轉換字符串
'54cbaabc789'                        #轉換后的字符串

    3.X下的演示過程:

>>> map = str.maketrans('123','abc') >>> s = '54321123789'
>>> s.translate(map) '54cbaabc789'

 2.X使用了string的maketrans函數,而3.X使用了str的maketrans函數,除了這一點,使用方法是基本相同的。若指定字符串中要刪除的字符時,使用就會略有不同,如下:
    2.X下的演示過程:

>>> import string >>> map = string.maketrans('123', 'abc') >>> s = '54321123789'
>>> s.translate(map, '78')        #除了轉換,還要刪除字符串中的字符'7','8'
'54cbaabc9'               #轉換后的字符串沒有字符'7','8'

    3.X下的演示過程:

>>> map = str.maketrans('123','abc', '78')#要刪除的字符需要在這指定
>>> s = '54321123789'
>>> s.translate(map) '54cbaabc9'

 str.partition(sep) --> (head, sep, tail)     根據指定的分隔符將字符串進行分割(返回一個3元的元組,第一個為分隔符左邊的子串,第二個為分隔符本身,第三個為分隔符右邊的子串)
注:str.partition(sep) 是從前往后查找 (從左往右)

  str.rpartition(sep)  是從后面開始查找 (從右往左)

str = 'learn Python is so easy'
print(str.partition('is')) #('learn Python ', 'is', ' so easy')
print(str.partition('ii')) #('learn Python is so easy', '', '')#如果字符串中沒有'ii',將返回整個字符串作為第一個,分割的本身以及尾部為空
print(str.partition('learn')) #('', 'learn', ' Python is so easy')
print(str.partition('easy')) #('learn Python is so ', 'easy', '')

與 find() rfind() 類似,不同的是如果找不到,就會引發 ValueError
str.index(sub[, start[, end]]); --> String         把字符串中的 old(舊字符串)替換成 new(新字符串),如果指定第三個參數max,則替換不超過 max 次。str.rindex(sub[, start[, end]]) --> String    返回子字符串 str 在字符串中最后出現的位置,如果沒有匹配的字符串會報異常,你可以指定可選參數[beg:end]設置查找的區間。

str = 'this is replace old old old text'
print(str.replace('old', 'new')) #this is replace new new new text
print(str.replace('old', 'new',1))#指定只替換幾個 #this is replace new old old text
print(str.replace('old', 'new',2)) #this is replace new new old text
print(str.rindex('old',10,20))#查找最后出線的位置(下標) #'16'
print(str.rindex('s',0,7))# #'6'

  str.split(sep=None, maxsplit=-1) --> list    通過指定分隔符對字符串進行切片,如果參數num有指定值,則僅分隔 num 個子字符串 
 str.rsplit(sep=None, maxsplit=-1)          從后往前
                        如果字符串開頭/結尾包含空格字符串則以非空格字符串后的第一個空格為分隔符

print('1,2,3'.split(','), '1, 2, 3'.rsplit())#split從前往后; rsplit從后往前 #['1', '2', '3'] ['1,', '2,', '3']

#如果參數num有指定值,則僅分隔 num 個子字符串
print('1,2,3'.split(',', maxsplit=1),  '1,2,3'.rsplit(',', maxsplit=1))#此處的意思就是僅分隔1次(最多分拆次數) #['1', '2,3'] ['1,2', '3']

print('1 2 3'.split(), '1 2 3'.rsplit())#此處是以默認值分隔,默認值為空格 #['1', '2', '3'] ['1', '2', '3']

print('test test test'.split(maxsplit=1), '1 2 3'.rsplit(maxsplit=1))#此處直接寫拆分次數,那么就是默認值(空格)分隔 #['test', 'test test'] ['1 2', '3']

print(' tttt test test '.split(), ' tttt test test '.rsplit())#如果字符串開頭/結尾包含空格字符串則以非空格字符串后的第一個空格為分隔符 #['tttt', 'test', 'test'] ['tttt', 'test', 'test']

print('1,2,,,3,'.split(','), '1,2,,,3,'.rsplit(',')) #(['1', '2', '', '', '3', ''] ['1', '2', '', '', '3', ''])

print(''.split()) #[]

print(''.split('a')) #['']

print('bcd'.split('a')) #['bcd']

print('bcd'.split(None)) #['bcd']

str.splitlines([keepends])  --> List    字符串以換行符為分隔符拆分,去掉行界符;如果keepends為True,保留行界符,能被識別的行界符參照官方文檔

print('HOW\nSOFT\nWORKS'.splitlines())#字符串以換行符為分隔符拆分,去掉換行符; #['HOW', 'SOFT', 'WORKS']
print('HOW\nSOFT\nWORKS'.splitlines(True))#如果keepends為True,保留換行符 #['HOW\n', 'SOFT\n', 'WORKS']

print(''.splitlines(), ''.split('\n'))#注意兩者的區別 #([] [''])
print("One line\n".splitlines(), "Two line\n".split('\n'))#注意兩者的區別 #(['One line'] ['Two line', ''])

 能被識別的行界符:

Representation Description
\n Line Feed   換行
\r Carriage Return 回車
\r\n Carriage Return + Line Feed  回車+換行
\v or \x0b Line Tabulation  
\f or \x0c Form Feed 換頁
\x1c File Separator 文件分隔符
\x1d Group Separator  組分隔符
\x1e Record Separator 記錄分隔符號
\x85 Next Line (C1 Control Code)
\u2028 Line Separator  行分隔符
\u2029 Paragraph Separator 段落分隔符號

 

str.startswith(prefix[, start[, end]]) --> Bool (true or false)    用於檢查字符串是否是以指定子字符串開頭,如果是則返回 True,否則返回 False。如果參數 beg 和 end指定值,則在指定范圍內檢查。

print('Learn python in cnblogs'.startswith('Learn')) #True
print('Learn python in cnblogs'.startswith('test')) #False
print('Learn python in cnblogs'.startswith('python',6,12)) #True
print('Learn python in cnblogs'.startswith('python',1,5)) #False

 

 

str.swapcase() -- > String   用於對字符串的大小寫字母進行反轉(小寫轉大寫,大寫轉小寫)

print('張Dobi a123 ß'.swapcase())#這里的 ß 被轉成 SS 是一種大寫 #張dOBI A123 SS

但需要注意的是 s.swapcase().swapcase() == s 不一定為真:

u'\xb5' # 'µ' u'\xb5'.swapcase() # 'Μ' u'\xb5'.swapcase().swapcase() # 'μ' hex(ord(u'\xb5'.swapcase().swapcase())) Out[154]: '0x3bc'

這里 'Μ'(是 mu 不是 M) 的小寫正好與 'μ' 的寫法一致。

str.strip([chars]) -->String      返回"標題化"的字符串,就是說所有單詞都是以大寫開始,其余字母均為小寫。

print('learn python in cnblogs'.title()) #Learn Python In Cnblogs

 

str.upper() -->String    將字符串所有字母變為大寫,會自動忽略不可轉成大寫的字符。

print('學習Python 1 day !!!'.upper()) #學習PYTHON 1 DAY !!!

str.zfill(width) --> String     用 '0' 填充字符串,並返回指定寬度的字符串。
注:正常一般是從字符串的左邊開始填充,如指定長度小於字符串長度則返回原字符串

print('A'.zfill(5)) #0000A
print('--'.zfill(5)) #-000-
print('\'\''.zfill(5)) #000''
print('AAAAAAAAAAAA'.zfill(6)) #AAAAAAAAAAAA
print('AAAAAAAAAAAA'.zfill(15)) #000AAAAAAAAAAAA
轉載鏈接:http://www.cnblogs.com/PeterZhang1520389703/p/7647160.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM