4.7. Text Sequence Type — str
Python中的文本數(shù)據(jù)由str
對(duì)象或strings
處理。字符串是Unicode編碼的不可變序列。字符串文字以各種方式寫入:
- 單引號(hào):
'允許嵌入"雙"引號(hào)'
- 雙引號(hào):
"允許嵌入'單'引號(hào)"
。 - 三重引號(hào):
'''三個(gè)單引號(hào)'''
,"""三個(gè)雙引號(hào)"""
三重引用的字符串可能會(huì)跨越多行 - 所有相關(guān)的空白字符都將包含在字符串文字中。
兩個(gè)字符串文字之間如果只有空格,則將被隱式轉(zhuǎn)換為單個(gè)字符串文字。也就是說:
>>>'span' 'eggs'
'spaneggs'
請(qǐng)參閱String and Bytes literals了解更多關(guān)于各種形式的字符串的信息,包括支持的轉(zhuǎn)義序列和r
(raw
)前綴,禁用大多數(shù)轉(zhuǎn)義序列處理等。
字符串也可以使用str
構(gòu)造函數(shù)從其他對(duì)象創(chuàng)建。
由于Python沒有單獨(dú)的character
類型,索引字符串會(huì)產(chǎn)生長度為1的字符串。也就是說,對(duì)于非空字符串s
,s [0] == s [0:1]
。
Python也沒有可變的字符串類型,但str.join()
或io .StringIO
可用于從多個(gè)片段高效地構(gòu)建字符串。
版本3.3中更改:為了向后兼容Python 2系列,字符串文字再次允許使用u
前綴。它對(duì)字符串文字的含義沒有影響,不能與“r”前綴組合。
class str(object='')
class str(object=b'', encoding='utf-8', errors='strict') # 針對(duì)byte-like字符串
返回object的string
表示。如果未提供object
,則返回空字符串。否則,str()
的行為取決于是否給出encoding
或errors
,如下所示:
如果encoding
和errors
都沒有給出,str(object)
返回object .__ str__()
,這是object
的informal
或可打印的字符串表示形式。對(duì)于字符串對(duì)象,這是字符串本身。如果object
沒有__str__()
方法,那么str ()
回退到repr(object)
。
如果給出encoding
或errors
中的至少一個(gè),object
應(yīng)該是bytes-like object
(例如bytes
或bytearray
)。在這種情況下,如果object
是bytes
(或bytearray
)對(duì)象,那么str(bytes,encoding,errors)
等同于bytes.decode(encoding,errors)
。否則,在調(diào)用bytes.decode()
之前獲取緩沖區(qū)對(duì)象的字節(jié)對(duì)象。
不帶參數(shù)encoding
和errors
的將bytes
對(duì)象傳遞給str()
屬于返回informal
字符串表示形式的第一種情況
>>> str(b'Zoot!')
"b'Zoot!'"
4.7.1. String Methods
字符串支持所有通用的序列方法,還支持以下所述的方法
字符串還支持兩種格式的字符串格式,一種提供了很大的靈活性和定制(參見str.format()
,Format String Syntax
和Custom String Formatting
,另一種基于Cprintf
樣式格式處理的類型范圍較窄,稍微難以正確使用,但對(duì)于可處理的情況通常更快(printf-style String Formatting
)。
標(biāo)準(zhǔn)庫的Text Processing Services
部分涵蓋了許多其他模塊,它們提供了各種文本相關(guān)的工具(包括re
模塊中的正則表達(dá)式支持)。
str.capitalize()
返回字符串的副本: 除了第一個(gè)字符變?yōu)榇髮懲?數(shù)字不變),其他的所有字符強(qiáng)制變成小寫。
>>>'123aBcDeFg'.capitalize()
'123abcdefg'
str.casefold()
返回字符串的副本:Casefolded strings may be used for caseless matching.
casefold
類似于lower
,但更具侵略性,因?yàn)樗荚趧h除字符串中的所有案例區(qū)別。例如,德語小寫字母?
等同于ss
。由于它已經(jīng)是小寫字母,lower()
對(duì)于?
不起作用 ;但是casefold()
可以將其轉(zhuǎn)換為ss
。
>>>'?'.lower()
'?'
>>>'?'.casefold()
'ss'
Unicode標(biāo)準(zhǔn)的第3.13節(jié)描述了casefold的算法。
New in version 3.3.
str.center(width[, fillchar])
返回一個(gè)新的字符串:原本的字符串居中顯示在一個(gè)長度為width
的字符串中。填充是使用指定的fillchar
(默認(rèn)是ASCII中的空格' ')完成的。如果width
小于或等于len(s)
,則返回原始字符串。
>>>r = '1234'
>>>r.center(10) # str.center(width) width > len(r)
' 1234 '
>>>r.center(3) # str.center(width) width <= len(r)
'1234'
>>>r.center(10,'.') # str.center(width, fillchar)
'...1234...'
>>>r
'1234'
str.count(sub[, start[, end]])
返回范圍[start,end]中子字符串sub
的非重疊次數(shù)。可選參數(shù)start
和end
為切片符號(hào)。
str.encode(encoding="utf-8", errors="strict")
以字節(jié)對(duì)象的形式返回字符串的編碼版本。默認(rèn)編碼是“utf-8”。 給出errors
參數(shù)來設(shè)置不同的錯(cuò)誤處理方案。 errors
的默認(rèn)值是'strict',這意味著編碼錯(cuò)誤會(huì)引發(fā)UnicodeError
。其他可能的值是'ignore','replace','xmlcharrefreplace','backslashreplace'和通過codecs.register_error()
注冊(cè)的任何其他名稱,請(qǐng)參見[Error Handlers
]一節(jié)。有關(guān)可能的編碼列表,請(qǐng)參見[Standard Encodings
]部分。
# errors:
# strict
# ignore
# replace
# xmlcharrefreplace
# backslashreplace
# 通過codecs.register_error()注冊(cè)的任何其他名稱
Changed in version 3.1: Support for keyword arguments added.
str.endswith(suffix[, start[, end]])
如果字符串以指定的suffix
結(jié)尾,則返回True
,否則返回False
。 suffix
也可以是一個(gè)由后綴組成的元組。如果有start
參數(shù),則測試從start
位置開始。如果有stop
參數(shù),則測試在stop
位置停止
>>>r = 'abcdefgxyz'
>>>r.endswith('xyz') # 匹配到xyz
True
>>>r.endswith(('xyz', 'z')) # 使用元組,匹配到xyz
True
>>>r.endswith(('opq', 'rst','xyz'), -3, len(r)) # 使用元組, (len(r) - 3, len(r))匹配到xyz
True
>>>r.endswith(('opq', 'rst','xyz', 'xy'), -3, len(r) - 1) # 匹配到xy
True
str.expandtabs(tabsize=8)
返回字符串的副本,其中所有制表符由一個(gè)或多個(gè)空格替換,具體取決于當(dāng)前列和給定的制表符大小。tab替換出現(xiàn)在每個(gè)\t
字符出現(xiàn)的位置(tabsize默認(rèn)值是8)。當(dāng)要展開字符串時(shí),當(dāng)前列設(shè)置為零,字符串逐個(gè)檢查。如果該字符是一個(gè)制表符(\ t
),則在結(jié)果中插入一個(gè)或多個(gè)空格字符(取決于設(shè)置的tabsize的大小),直到當(dāng)前列等于下一個(gè)制表符位置(制表符本身不被復(fù)制).如果該字符是換行符(\ n
)或返回符號(hào)(\ r
),則復(fù)制該字符并將當(dāng)前列重置為零。任何其他字符都將被不變地復(fù)制,而當(dāng)前列增加1,無論打印時(shí)字符如何表示。
>>>'01\t012\t0123\t01234'.expandtabs()
'01 012 0123 01234'
>>> '01\t012\t0123\t01234'.expandtabs(4)
'01 012 0123 01234'
str.find(sub[, start[, end]])
返回字符串中離開頭最近的索引,其中子字符串sub
在切片的[start:end]內(nèi)找到。可選參數(shù)start
和end
被解釋為切片符號(hào)。如果未找到sub
,則返回-1
。
Note:
find
方法只應(yīng)該用于你想知道sub
的位置,如果想檢查sub
是否存在,請(qǐng)使用in
代替:
>>>'Py' in 'Python'
True
str.format(*args, **kwargs)
執(zhí)行字符串格式化操作。調(diào)用此方法的字符串可以包含由大括號(hào){}
分隔的文本文本或替換字段。每個(gè)替換字段包含位置參數(shù)的數(shù)字索引或關(guān)鍵字參數(shù)的名稱。返回字符串的副本,其中每個(gè)替換字段被相應(yīng)參數(shù)的字符串值替換。
>>>"The sum of 1 + 2 is {0}".format(1+2)
'The sum of 1 + 2 is 3'
>>>'{a} + {b} = {sum}'.format(a=1, b=2, sum=(1 + 2))
'1 + 2 = 3'
有關(guān)可以在格式字符串中指定的各種格式選項(xiàng)的說明,請(qǐng)參見[Format String Syntax
]。
Note
當(dāng)使用n
類型(例如{:n}'.format(1234)
)格式化一個(gè)數(shù)字([int
],[float
],[float
]和其子類)時(shí),函數(shù)將LC_CTYPE
語言環(huán)境臨時(shí)設(shè)置為LC_NUMERIC
語言環(huán)境,以解碼localeconv()
的decimal_point
和thousands_sep
字段,如果它們是非ASCII或長于1個(gè)字節(jié),并且LC_NUMERIC語言環(huán)境不同于LC_CTYPE
區(qū)域設(shè)置。此臨時(shí)更改會(huì)影響其他線程。
locale 是根據(jù)計(jì)算機(jī)用戶所使用的語言,所在國家或者地區(qū),以及當(dāng)?shù)氐奈幕瘋鹘y(tǒng)
所定義的一個(gè)軟件運(yùn)行時(shí)的語言環(huán)境。通常情況下它可以按照涉及使用習(xí)慣分為12大類:
- 語言符號(hào)及其分類(LC_CTYPE)
- 數(shù)字(LC_NUMBERIC)
- 比較習(xí)慣(LC_COLLATE)
- 時(shí)間顯示格式(LC_TIME)
- 貨幣單位(LC_MONETARY)
- 信息主要是提示信息,錯(cuò)誤信息,狀態(tài)信息,標(biāo)題,標(biāo)簽,按鈕和菜單等(LC_MESSAGES)
- 行么書寫方式(LC_NAME)
- 地址書寫方式(LC_ADDRESS)
- 電話號(hào)碼書寫方式(LC_TELEPHONE)
- 度量衡表達(dá)方式(LC_MEASUREMENT)
- 默認(rèn)紙張尺寸大小(LC_PAPER)
- 對(duì)locale 自身包含信息的概述(LC_IDENTIFICATION)
- 除此之外還有一個(gè)LANGUAGE參數(shù),它與LC_MESSAGES相似
Changed in version 3.6.5: 在使用n
類型格式化數(shù)字時(shí),函數(shù)在某些情況下會(huì)將LC_CTYPE
語言環(huán)境臨時(shí)設(shè)置為LC_NUMERIC
類型。
str.format_map(mapping)
類似于str.format(mapping)
,除了直接使用mapping
而不是復(fù)制到dict
。例如如果mapping
是一個(gè)字典子類,這是有用的:
>>>class Default(dict):
... def __missing__(self, key):
... return key
...
>>> '{name} was born in {country}'.format_map(Default(name='Guido'))
'Guido was born in country'
New in version 3.2.
str.index(sub[, start[, end]])
類似find()
,但在未找到子字符串時(shí)引發(fā)ValueError
。
str.isalnum()
如果字符串中的所有字符都是字母數(shù)字且至少有一個(gè)字符,則返回true,否則返回false。如果以下其中一個(gè)返回True
:c.isalpha()
,c.isdecimal()
,c.isdigit()
或c.isnumeric()
,則字符c
為isalnum
。
str.isalpha()
如果字符串中的所有字符都是字母,并且至少有一個(gè)字符,則返回true,否則返回false。字母字符是在Unicode字符數(shù)據(jù)庫中定義為“Letter”的那些字符,即具有一般類別屬性是“Lm”,“Lt”,“Lu”,“Ll”或“Lo”之一的字符(參閱附錄)。請(qǐng)注意,這與Unicode標(biāo)準(zhǔn)中定義的“字母”屬性不同。
str.isdecimal()
如果字符串中的所有字符都是十進(jìn)制字符,并且至少有一個(gè)字符,則返回true,否則返回false。十進(jìn)制字符是那些可以用來形成基數(shù)為10的數(shù)字,例如U + 0660,阿拉伯?dāng)?shù)字0。形式上,十進(jìn)制字符是Unicode常規(guī)類別“Nd”中的字符。
str.isdigit()
如果字符串中的所有字符都是數(shù)字并且至少有一個(gè)字符,則返回true,否則返回false。數(shù)字包含需要特殊處理的十進(jìn)制字符和數(shù)字,例如兼容性上標(biāo)數(shù)字。這包括不能用來形成基數(shù)為10的數(shù)字,如Kharosthi數(shù)字。形式上,數(shù)字是具有屬性值Numeric_Type = Digit或Numeric_Type = Decimal的字符。
str.isidentifier()
如果字符串是符合語言定義的有效標(biāo)識(shí)符,則返回true. 標(biāo)識(shí)符和關(guān)鍵字。
使用keyword.iskeyword()
來測試保留的標(biāo)識(shí)符,如def
和class
。
str.islower()
如果字符串中的所有cased字符都是小寫字母,并且至少有一個(gè)cased字符,則返回true,否則返回false。
str.isnumeric()
如果字符串中的所有字符都是數(shù)字字符,并且至少有一個(gè)字符,則返回true,否則返回false。數(shù)字字符包括digit字符和具有Unicode數(shù)字值屬性的所有字符,例如U + 2155,VULGAR分?jǐn)?shù)ONE FIFTH。形式上,數(shù)字字符是具有屬性值Numeric_Type = Digit,Numeric_Type = Decimal或Numeric_Type = Numeric的字符。
str.isprintable()
如果字符串中的所有字符都可打印或字符串為空,則返回true,否則返回false。非可打印字符是在Unicode字符數(shù)據(jù)庫中定義為“Other”或“Separator”的字符,但ASCII空格(0x20)被認(rèn)為是可打印的。 (注意,在這個(gè)上下文中的可打印字符是那些在字符串上調(diào)用repr()
時(shí)不應(yīng)該被轉(zhuǎn)義的字符,它不會(huì)影響寫入sys.stdout
或sys.stderr
)。
str.isspace()
如果字符串中只有空格字符,并且至少有一個(gè)字符,則返回true,否則返回false。空格字符是在Unicode字符數(shù)據(jù)庫中定義為“Other”或“Separator”的那些字符,以及具有“WS”,“B”或“S”之一的雙向?qū)傩缘哪切┳址?/p>
str.istitle()
如果字符串是一個(gè)標(biāo)題字符串,并且至少有一個(gè)字符,則返回true,例如,大寫字符只能跟在uncased字符之后,而小寫字符只能在一個(gè)cased字符之后。否則返回false。
str.isupper()
如果字符串中的所有cased字符都是大寫且至少有一個(gè)cased字符,則返回true,否則返回false。
str.join(iterable)
返回一個(gè)字符串,它是iterable中字符串的串聯(lián)。如果
iterable中有任何非字符串值,包括
bytes對(duì)象,則會(huì)引發(fā)
TypeError`。元素之間的分隔符是提供此方法的字符串。
str.ljust(width[, fillchar])
返回一個(gè)新的字符串。如果width<=len(str)
,則字符串不變,否則將字符串左對(duì)齊,并且在后面填充fillchar
(默認(rèn)是ASCII的空格).
str.lower()
返回字符串的一個(gè)副本,并將所有字符轉(zhuǎn)換為小寫字母。
str.lstrip([chars])
返回刪除前導(dǎo)字符的字符串的副本。 chars
參數(shù)是一個(gè)字符串,指定要?jiǎng)h除的字符集。如果省略或者None
,chars
參數(shù)默認(rèn)刪除空格。 chars
參數(shù)不是一個(gè)前綴;相反,它的值的所有組合都被剝離了:
>>> ' spacious '.lstrip()
'spacious '
>>> 'www.example.com'.lstrip('cmowz.')
'example.com'
static str.maketrans(x[, y[, z]])
這個(gè)靜態(tài)方法返回一個(gè)可用于str.translate()
的轉(zhuǎn)換表
如果只有一個(gè)參數(shù),它必須是一個(gè)將Unicode序數(shù)(整數(shù))或字符(長度為1的字符串)映射到Unicode序號(hào),字符串(任意長度)或None
的字典。字符鍵將被轉(zhuǎn)換為序號(hào)。
如果有兩個(gè)參數(shù),它們必須是長度相等的字符串,并且在結(jié)果字典中,x
中的每個(gè)字符將映射到y
中相同位置的字符。
如果有第三個(gè)參數(shù),它必須是一個(gè)字符串,其字符將被映射到結(jié)果中的None
。
>>>l = '123qwe'
>>>l.maketrans({'1':'2'})
{49: '2'}
>>>l.maketrans('123','456')
{49: 52, 50: 53, 51: 54}
>>>l.maketrans('123','456', 'qwe')
{49: 52, 50: 53, 51: 54, 113: None, 119: None, 101: None}
str.partition(sep)
在sep
的第一個(gè)出現(xiàn)處拆分字符串,并返回包含分隔符之前的部分,分隔符本身和分隔符之后的部分的三元組。如果找不到分隔符,則返回包含字符串本身及兩個(gè)空字符串的三元組。
>>>l.partition('3')
('12', '3', 'qwe')
>>>l.partition('0')
('123qwe', '', '')
>>>l.partition('234')
('123qwe', '', '')
>>>l.partition('23')
('1', '23', 'qwe')
str.replace(old, new[, count])返回所有出現(xiàn)的子字符串
old替換為
new的字符串的副本。如果給出可選參數(shù)
count,則只會(huì)替換
count`次數(shù)。
>>>l = 'youyouyouyou'
>>>l.replace('y', 'r', 2)
'rourouyouyou'
str.rfind(sub[, start[, end]])
返回找到substring sub
的字符串中的最高索引,使得sub
包含在s [start:end]
內(nèi)。可選參數(shù)start
和end
被解釋為切片符號(hào)。當(dāng)失敗時(shí)返回-1
。
對(duì)比find
方法,此方法為從后往前查找(rfind-->right find)
str.rindex(sub[, start[, end]])
和rfind()
一樣,但是在找不到子字符串sub
時(shí)引發(fā)ValueError
。
對(duì)比index
方法,此方法為從后往前查找(rindex-->right index)
str.rjust(width[, fillchar])
返回字符串右對(duì)齊的長度為width
的字符串。填充是使用指定的fillchar
(默認(rèn)是ASCII中的空格)完成的。如果width
小于或等于len(s)
,則返回原始字符串。
對(duì)比ljust
方法,此方法為右對(duì)齊。
str.rpartition(sep)
在sep
的最后出現(xiàn)處拆分字符串,并返回包含分隔符之前的部分,分隔符本身和分隔符之后的部分的三元組。如果未找到分隔符,則返回包含兩個(gè)空字符串的三元組,然后返回字符串本身。
對(duì)比partition
方法,rpartition從右到左遍歷。
str.rsplit(sep=None, maxsplit=-1)
返回字符串中的單詞列表,使用sep
作為分隔符字符串。如果給出maxsplit
,最多分割maxsplit
次,此方法從最右邊開始分割。如果sep沒有指定或者沒有,則任何空格字符串都是分隔符。除了從右邊分割外,[rsplit()
]的行為就像[split()
],這在下面詳細(xì)描述。
str.rstrip([chars])
返回刪除了尾隨字符的字符串的副本。 chars
參數(shù)是一個(gè)字符串,指定要?jiǎng)h除的字符集。如果省略或者None
,chars
參數(shù)默認(rèn)刪除空格。 chars
參數(shù)不是后綴;相反,其值的所有組合都被剝離:
>>> ' spacious '.rstrip()
' spacious'
>>> 'mississippi'.rstrip('ipz')
'mississ'
str.split(sep=None, maxsplit=-1)
返回字符串中的單詞列表,使用sep作為分隔符字符串。如果給出maxsplit
,最多分割maxsplit
次(因此,該列表最多只有maxsplit + 1
個(gè)元素)。如果maxsplit沒有被指定或者是-1
,那么分割的數(shù)量是沒有限制的(返回所有可能的分割)。
如果給定sep
,則分割時(shí)連續(xù)的分隔符不會(huì)被分組在一起,并被視為分隔空字符串(例如'1,2'.split(',')
返回['1','','' 2' ]
)。 sep
參數(shù)可以由多個(gè)字符組成(例如,'1<>2<>3'.split('<>')
返回['1','2','3']
) 。用指定的分隔符分割空字符串會(huì)返回['']
。
For example:
>>>'1,2,3'.split(',')
['1', '2', '3']
>>> '1,2,3'.split(',', maxsplit=1)
['1', '2,3']
>>> '1,2,,3,'.split(',')
['1', '2', '', '3', '']
如果未指定* sep *或者為None,則應(yīng)用不同的分割算法:將連續(xù)空白的運(yùn)行視為單個(gè)分隔符,并且如果該字符串具有前導(dǎo)或結(jié)果,則在開始或結(jié)束時(shí)不會(huì)包含空字符串或拖尾的空白。因此,將一個(gè)空字符串或一個(gè)只包含空格的字符串與一個(gè)“None”分隔符分開將返回[]
。
For example:
>>>'1 2 3'.split()
['1', '2', '3']
>>> '1 2 3'.split(maxsplit=1)
['1', '2 3']
>>> ' 1 2 3 '.split()
['1', '2', '3']
str.splitlines([keepends])
返回字符串中l(wèi)ines的列表,在lines邊界處突破。換行符不包含在結(jié)果列表中,除非* keepends *被給出且為真。
此方法分割在以下行邊界上。特別是,邊界是universal newlines
的超集:
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 |
Changed in version 3.2:將\v
和\f
添加到行邊界列表中。
For example:
>>> 'ab c\n\nde fg\rkl\r\n'.splitlines()
['ab c', '', 'de fg', 'kl']
>>> 'ab c\n\nde fg\rkl\r\n'.splitlines(keepends=True)
['ab c\n', '\n', 'de fg\r', 'kl\r\n']
Unlike [split()
] when a delimiter string sep is given, this method returns an empty list for the empty string, and a terminal line break does not result in an extra line:
與[split()
]不同,此方法返回空字符串的空列表,并且終端行分隔不會(huì)導(dǎo)致多余行:
>>>"".splitlines()
[]
>>> "One line\n".splitlines()
['One line']
For comparison, split('\n')
gives:
>>>''.split('\n')
['']
>>> 'Two lines\n'.split('\n')
['Two lines', '']
str.startswith(prefix[, start[, end]])
如果字符串以prefix開頭,則返回True
,否則返回False
。 prefix也可以是一個(gè)前綴元組來查找。使用可選的start
,測試字符串從該位置開始。使用可選的end
,停止在該位置比較字符串。
類比endswith.
str.strip([chars])
返回刪除前導(dǎo)字符和尾隨字符的字符串副本。 * chars 參數(shù)是一個(gè)字符串,指定要?jiǎng)h除的字符集。如果省略或者None
, chars *參數(shù)默認(rèn)刪除空格。 * chars *參數(shù)不是前綴或后綴;相反,其值的所有組合都被剝離:
>>>' spacious '.strip()
'spacious'
>>> 'www.example.com'.strip('cmowz.')
'example'
從字符串中剝離最外部的前導(dǎo)和尾部chars
參數(shù)值。從前端刪除字符,直到到達(dá)chars
中字符集中不包含的字符串字符。尾端發(fā)生類似的行為。例如:
>>>comment_string = '#....... Section 3.2.1 Issue #32 .......'
>>> comment_string.strip('.#! ')
'Section 3.2.1 Issue #32'
str.swapcase()
返回大寫字符轉(zhuǎn)換為小寫字符串的副本,反之亦然。請(qǐng)注意,s.swapcase().swapcase()== s
不一定成立。
str.title()
返回字符串的字幕版本,其中字以大寫字符開頭,其余字符為小寫字母。
For example:
>>> 'Hello world'.title()
'Hello World'
該算法使用簡單的與語言無關(guān)的單詞定義作為連續(xù)字母組。這個(gè)定義在很多情況下都有效,但是這意味著收縮和占有者的撇號(hào)(')形成了單詞邊界,這可能不是理想的結(jié)果:
>>>"they're bill's friends from the UK".title()
"They'Re Bill'S Friends From The Uk"
可以使用正則表達(dá)式構(gòu)造撇號(hào)的解決方法:
>>> import re
>>> def titlecase(s):
... return re.sub(r"[A-Za-z]+('[A-Za-z]+)?",
... lambda mo: mo.group(0)[0].upper() +
... mo.group(0)[1:].lower(),
... s)
...
>>> titlecase("they're bill's friends.")
"They're Bill's Friends."
str.translate(table)
通過給定的轉(zhuǎn)換表返回每個(gè)字符已映射的字符串的副本。該表必須是通過__getitem __()
實(shí)現(xiàn)索引的對(duì)象,通常是mapping
或sequence
。當(dāng)通過Unicode序數(shù)(整數(shù))索引時(shí),表對(duì)象可以執(zhí)行以下任何操作:返回Unicode序號(hào)或字符串,將字符映射到一個(gè)或多個(gè)其他字符;返回None
,從返回字符串中刪除字符;或引發(fā)LookupError
異常,將字符映射到自身。
你可以使用[str.maketrans()
]來創(chuàng)建不同格式的字符到字符映射的轉(zhuǎn)換映射。
另請(qǐng)參閱codecs
模塊,以獲得更靈活的自定義字符映射方法。
str.upper()
返回字符串的所有字符轉(zhuǎn)換為大寫的副本。請(qǐng)注意,如果s
包含uncased字符,或者如果生成的字符的Unicode類別不是“Lu”(Letter,大寫),則str.upper().isupper()
可能是False
。比如: “Lt”(Letter,titlecase)。
Unicode標(biāo)準(zhǔn)的第3.13節(jié)描述了The uppercasing algorithm
.
str.zfill(width)
返回一個(gè)左邊填充了ASCII0
數(shù)字的字符串的副本,以產(chǎn)生一個(gè)長度為width
的字符串。 前導(dǎo)符號(hào)前綴('+'
/`` - ')是通過在符號(hào)字符之后插入填充符*而不是之前處理的。 如果
width小于或等于
len(s)`,則返回原始字符串
For example:
>>>"42".zfill(5)
'00042'
>>> "-42".zfill(5)
'-0042'
4.7.2. printf
-style String Formatting
Note
The formatting operations described here exhibit a variety of quirks that lead to a number of common errors (such as failing to display tuples and dictionaries correctly). Using the newer [formatted string literals] or the [str.format()
] interface helps avoid these errors. These alternatives also provide more powerful, flexible and extensible approaches to formatting text.
這里描述的格式化操作表現(xiàn)出各種各樣的怪癖,導(dǎo)致許多常見錯(cuò)誤(如未能正確顯示元組和字典)。使用新的formatted string literals
或str.format()
接口有助于避免這些錯(cuò)誤。這些替代方案還提供了更強(qiáng)大,靈活和可擴(kuò)展的方法來格式化文本。
字符串對(duì)象有一個(gè)獨(dú)特的內(nèi)置操作:%
操作符(模)。這也被稱為字符串* formatting 或 interpolation 運(yùn)算符。給定format%values
(其中 format 是一個(gè)字符串), format 中的%
轉(zhuǎn)換規(guī)范被替換為 values *的零個(gè)或多個(gè)元素。其效果與在C語言中使用sprintf()
類似。
If format requires a single argument, values may be a single non-tuple object. [[5]]] Otherwise, values must be a tuple with exactly the number of items specified by the format string, or a single mapping object (for example, a dictionary).
A conversion specifier contains two or more characters and has the following components, which must occur in this order:
- The
'%'
character, which marks the start of the specifier. - Mapping key (optional), consisting of a parenthesised sequence of characters (for example,
(somename)
). - Conversion flags (optional), which affect the result of some conversion types.
- Minimum field width (optional). If specified as an
'*'
(asterisk), the actual width is read from the next element of the tuple in values, and the object to convert comes after the minimum field width and optional precision. - Precision (optional), given as a
'.'
(dot) followed by the precision. If specified as'*'
(an asterisk), the actual precision is read from the next element of the tuple in values, and the value to convert comes after the precision. - Length modifier (optional).
- Conversion type.
When the right argument is a dictionary (or other mapping type), then the formats in the string must include a parenthesised mapping key into that dictionary inserted immediately after the '%'
character. The mapping key selects the value to be formatted from the mapping. For example:
>>>print('%(language)s has %(number)03d quote types.' %
... {'language': "Python", "number": 2})
Python has 002 quote types.
In this case no *
specifiers may occur in a format (since they require a sequential parameter list).
The conversion flag characters are:
Flag | Meaning |
---|---|
'#' |
The value conversion will use the “alternate form” (where defined below). |
'0' |
The conversion will be zero padded for numeric values. |
'-' |
The converted value is left adjusted (overrides the '0' conversion if both are given). |
' ' |
(a space) A blank should be left before a positive number (or empty string) produced by a signed conversion. |
'+' |
A sign character ('+' or '-' ) will precede the conversion (overrides a “space” flag). |
A length modifier (h
, l
, or L
) may be present, but is ignored as it is not necessary for Python – so e.g. %ld
is identical to %d
.
The conversion types are:
Conversion | Meaning | Notes |
---|---|---|
'd' |
Signed integer decimal. | |
'i' |
Signed integer decimal. | |
'o' |
Signed octal value. | (1) |
'u' |
Obsolete type – it is identical to 'd' . |
(6) |
'x' |
Signed hexadecimal (lowercase). | (2) |
'X' |
Signed hexadecimal (uppercase). | (2) |
'e' |
Floating point exponential format (lowercase). | (3) |
'E' |
Floating point exponential format (uppercase). | (3) |
'f' |
Floating point decimal format. | (3) |
'F' |
Floating point decimal format. | (3) |
'g' |
Floating point format. Uses lowercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise. | (4) |
'G' |
Floating point format. Uses uppercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise. | (4) |
'c' |
Single character (accepts integer or single character string). | |
'r' |
String (converts any Python object using repr() ). |
(5) |
's' |
String (converts any Python object using str() ). |
(5) |
'a' |
String (converts any Python object using ascii() ). |
(5) |
'%' |
No argument is converted, results in a '%' character in the result. |
Notes:
The alternate form causes a leading octal specifier (
'0o'
) to be inserted before the first digit.The alternate form causes a leading
'0x'
or'0X'
(depending on whether the'x'
or'X'
format was used) to be inserted before the first digit.-
The alternate form causes the result to always contain a decimal point, even if no digits follow it.
The precision determines the number of digits after the decimal point and defaults to 6.
-
The alternate form causes the result to always contain a decimal point, and trailing zeroes are not removed as they would otherwise be.
The precision determines the number of significant digits before and after the decimal point and defaults to 6.
If precision is
N
, the output is truncated toN
characters.See PEP 237.
Since Python strings have an explicit length, %s
conversions do not assume that '\0'
is the end of the string.
Changed in version 3.1: %f
conversions for numbers whose absolute value is over 1e50 are no longer replaced by %g
conversions.
附錄:
Unicode常規(guī)類別 | |
---|---|
類別 | 說明 |
Lu | 字母,大寫 |
Ll | 字母,小寫 |
Lt | 字母,詞首字母大寫 |
Lm | 字母,修飾符 |
Lo | 字母,其他 |
Mn | 標(biāo)記,非間距 |
Mc | 標(biāo)記,間距組合 |
Me | 標(biāo)記,封閉 |
Nd | 數(shù)字,十進(jìn)制數(shù) |
Nl | 數(shù)字,字母 |
No | 數(shù)字,其他 |
Pc | 標(biāo)點(diǎn),連接符 |
Pd | 標(biāo)點(diǎn),短劃線 |
Ps | 標(biāo)點(diǎn),開始 |
Pe | 標(biāo)點(diǎn),結(jié)束 |
Pi | 標(biāo)點(diǎn),前引號(hào)(根據(jù)用途可能表現(xiàn)為類似 Ps 或 Pe) |
Pf | 標(biāo)點(diǎn),后引號(hào)(根據(jù)用途可能表現(xiàn)為類似 Ps 或 Pe) |
Po | 標(biāo)點(diǎn),其他 |
Sm | 符號(hào),數(shù)學(xué) |
Sc | 符號(hào),貨幣 |
Sk | 符號(hào),修飾符 |
So | 符號(hào),其他 |
Zs | 分隔符,空白 |
Zl | 分隔符,行 |
Zp | 分隔符,段落 |
Cc | 其他,控制 |
Cf | 其他,格式 |
Cs | 其他,代理項(xiàng) |
Co | 其他,私用 |
Cn | 其他,未賦值(不存在任何字符具有此屬性) |