4.7. Text Sequence Type — str
Python中的文本數據由str
對象或strings
處理。字符串是Unicode編碼的不可變序列。字符串文字以各種方式寫入:
- 單引號:
'允許嵌入"雙"引號'
- 雙引號:
"允許嵌入'單'引號"
。 - 三重引號:
'''三個單引號'''
,"""三個雙引號"""
三重引用的字符串可能會跨越多行 - 所有相關的空白字符都將包含在字符串文字中。
兩個字符串文字之間如果只有空格,則將被隱式轉換為單個字符串文字。也就是說:
>>>'span' 'eggs'
'spaneggs'
請參閱String and Bytes literals了解更多關于各種形式的字符串的信息,包括支持的轉義序列和r
(raw
)前綴,禁用大多數轉義序列處理等。
字符串也可以使用str
構造函數從其他對象創建。
由于Python沒有單獨的character
類型,索引字符串會產生長度為1的字符串。也就是說,對于非空字符串s
,s [0] == s [0:1]
。
Python也沒有可變的字符串類型,但str.join()
或io .StringIO
可用于從多個片段高效地構建字符串。
版本3.3中更改:為了向后兼容Python 2系列,字符串文字再次允許使用u
前綴。它對字符串文字的含義沒有影響,不能與“r”前綴組合。
class str(object='')
class str(object=b'', encoding='utf-8', errors='strict') # 針對byte-like字符串
返回object的string
表示。如果未提供object
,則返回空字符串。否則,str()
的行為取決于是否給出encoding
或errors
,如下所示:
如果encoding
和errors
都沒有給出,str(object)
返回object .__ str__()
,這是object
的informal
或可打印的字符串表示形式。對于字符串對象,這是字符串本身。如果object
沒有__str__()
方法,那么str ()
回退到repr(object)
。
如果給出encoding
或errors
中的至少一個,object
應該是bytes-like object
(例如bytes
或bytearray
)。在這種情況下,如果object
是bytes
(或bytearray
)對象,那么str(bytes,encoding,errors)
等同于bytes.decode(encoding,errors)
。否則,在調用bytes.decode()
之前獲取緩沖區對象的字節對象。
不帶參數encoding
和errors
的將bytes
對象傳遞給str()
屬于返回informal
字符串表示形式的第一種情況
>>> str(b'Zoot!')
"b'Zoot!'"
4.7.1. String Methods
字符串支持所有通用的序列方法,還支持以下所述的方法
字符串還支持兩種格式的字符串格式,一種提供了很大的靈活性和定制(參見str.format()
,Format String Syntax
和Custom String Formatting
,另一種基于Cprintf
樣式格式處理的類型范圍較窄,稍微難以正確使用,但對于可處理的情況通常更快(printf-style String Formatting
)。
標準庫的Text Processing Services
部分涵蓋了許多其他模塊,它們提供了各種文本相關的工具(包括re
模塊中的正則表達式支持)。
str.capitalize()
返回字符串的副本: 除了第一個字符變為大寫外(數字不變),其他的所有字符強制變成小寫。
>>>'123aBcDeFg'.capitalize()
'123abcdefg'
str.casefold()
返回字符串的副本:Casefolded strings may be used for caseless matching.
casefold
類似于lower
,但更具侵略性,因為它旨在刪除字符串中的所有案例區別。例如,德語小寫字母?
等同于ss
。由于它已經是小寫字母,lower()
對于?
不起作用 ;但是casefold()
可以將其轉換為ss
。
>>>'?'.lower()
'?'
>>>'?'.casefold()
'ss'
Unicode標準的第3.13節描述了casefold的算法。
New in version 3.3.
str.center(width[, fillchar])
返回一個新的字符串:原本的字符串居中顯示在一個長度為width
的字符串中。填充是使用指定的fillchar
(默認是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
的非重疊次數??蛇x參數start
和end
為切片符號。
str.encode(encoding="utf-8", errors="strict")
以字節對象的形式返回字符串的編碼版本。默認編碼是“utf-8”。 給出errors
參數來設置不同的錯誤處理方案。 errors
的默認值是'strict',這意味著編碼錯誤會引發UnicodeError
。其他可能的值是'ignore','replace','xmlcharrefreplace','backslashreplace'和通過codecs.register_error()
注冊的任何其他名稱,請參見[Error Handlers
]一節。有關可能的編碼列表,請參見[Standard Encodings
]部分。
# errors:
# strict
# ignore
# replace
# xmlcharrefreplace
# backslashreplace
# 通過codecs.register_error()注冊的任何其他名稱
Changed in version 3.1: Support for keyword arguments added.
str.endswith(suffix[, start[, end]])
如果字符串以指定的suffix
結尾,則返回True
,否則返回False
。 suffix
也可以是一個由后綴組成的元組。如果有start
參數,則測試從start
位置開始。如果有stop
參數,則測試在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)
返回字符串的副本,其中所有制表符由一個或多個空格替換,具體取決于當前列和給定的制表符大小。tab替換出現在每個\t
字符出現的位置(tabsize默認值是8)。當要展開字符串時,當前列設置為零,字符串逐個檢查。如果該字符是一個制表符(\ t
),則在結果中插入一個或多個空格字符(取決于設置的tabsize的大小),直到當前列等于下一個制表符位置(制表符本身不被復制).如果該字符是換行符(\ n
)或返回符號(\ r
),則復制該字符并將當前列重置為零。任何其他字符都將被不變地復制,而當前列增加1,無論打印時字符如何表示。
>>>'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]內找到??蛇x參數start
和end
被解釋為切片符號。如果未找到sub
,則返回-1
。
Note:
find
方法只應該用于你想知道sub
的位置,如果想檢查sub
是否存在,請使用in
代替:
>>>'Py' in 'Python'
True
str.format(*args, **kwargs)
執行字符串格式化操作。調用此方法的字符串可以包含由大括號{}
分隔的文本文本或替換字段。每個替換字段包含位置參數的數字索引或關鍵字參數的名稱。返回字符串的副本,其中每個替換字段被相應參數的字符串值替換。
>>>"The sum of 1 + 2 is {0}".format(1+2)
'The sum of 1 + 2 is 3'
>>>'{a} + = {sum}'.format(a=1, b=2, sum=(1 + 2))
'1 + 2 = 3'
有關可以在格式字符串中指定的各種格式選項的說明,請參見[Format String Syntax
]。
Note
當使用n
類型(例如{:n}'.format(1234)
)格式化一個數字([int
],[float
],[float
]和其子類)時,函數將LC_CTYPE
語言環境臨時設置為LC_NUMERIC
語言環境,以解碼localeconv()
的decimal_point
和thousands_sep
字段,如果它們是非ASCII或長于1個字節,并且LC_NUMERIC語言環境不同于LC_CTYPE
區域設置。此臨時更改會影響其他線程。
locale 是根據計算機用戶所使用的語言,所在國家或者地區,以及當地的文化傳統
所定義的一個軟件運行時的語言環境。通常情況下它可以按照涉及使用習慣分為12大類:
- 語言符號及其分類(LC_CTYPE)
- 數字(LC_NUMBERIC)
- 比較習慣(LC_COLLATE)
- 時間顯示格式(LC_TIME)
- 貨幣單位(LC_MONETARY)
- 信息主要是提示信息,錯誤信息,狀態信息,標題,標簽,按鈕和菜單等(LC_MESSAGES)
- 行么書寫方式(LC_NAME)
- 地址書寫方式(LC_ADDRESS)
- 電話號碼書寫方式(LC_TELEPHONE)
- 度量衡表達方式(LC_MEASUREMENT)
- 默認紙張尺寸大?。↙C_PAPER)
- 對locale 自身包含信息的概述(LC_IDENTIFICATION)
- 除此之外還有一個LANGUAGE參數,它與LC_MESSAGES相似
Changed in version 3.6.5: 在使用n
類型格式化數字時,函數在某些情況下會將LC_CTYPE
語言環境臨時設置為LC_NUMERIC
類型。
str.format_map(mapping)
類似于str.format(mapping)
,除了直接使用mapping
而不是復制到dict
。例如如果mapping
是一個字典子類,這是有用的:
>>>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()
,但在未找到子字符串時引發ValueError
。
str.isalnum()
如果字符串中的所有字符都是字母數字且至少有一個字符,則返回true,否則返回false。如果以下其中一個返回True
:c.isalpha()
,c.isdecimal()
,c.isdigit()
或c.isnumeric()
,則字符c
為isalnum
。
str.isalpha()
如果字符串中的所有字符都是字母,并且至少有一個字符,則返回true,否則返回false。字母字符是在Unicode字符數據庫中定義為“Letter”的那些字符,即具有一般類別屬性是“Lm”,“Lt”,“Lu”,“Ll”或“Lo”之一的字符(參閱附錄)。請注意,這與Unicode標準中定義的“字母”屬性不同。
str.isdecimal()
如果字符串中的所有字符都是十進制字符,并且至少有一個字符,則返回true,否則返回false。十進制字符是那些可以用來形成基數為10的數字,例如U + 0660,阿拉伯數字0。形式上,十進制字符是Unicode常規類別“Nd”中的字符。
str.isdigit()
如果字符串中的所有字符都是數字并且至少有一個字符,則返回true,否則返回false。數字包含需要特殊處理的十進制字符和數字,例如兼容性上標數字。這包括不能用來形成基數為10的數字,如Kharosthi數字。形式上,數字是具有屬性值Numeric_Type = Digit或Numeric_Type = Decimal的字符。
str.isidentifier()
如果字符串是符合語言定義的有效標識符,則返回true. 標識符和關鍵字。
使用keyword.iskeyword()
來測試保留的標識符,如def
和class
。
str.islower()
如果字符串中的所有cased字符都是小寫字母,并且至少有一個cased字符,則返回true,否則返回false。
str.isnumeric()
如果字符串中的所有字符都是數字字符,并且至少有一個字符,則返回true,否則返回false。數字字符包括digit字符和具有Unicode數字值屬性的所有字符,例如U + 2155,VULGAR分數ONE FIFTH。形式上,數字字符是具有屬性值Numeric_Type = Digit,Numeric_Type = Decimal或Numeric_Type = Numeric的字符。
str.isprintable()
如果字符串中的所有字符都可打印或字符串為空,則返回true,否則返回false。非可打印字符是在Unicode字符數據庫中定義為“Other”或“Separator”的字符,但ASCII空格(0x20)被認為是可打印的。 (注意,在這個上下文中的可打印字符是那些在字符串上調用repr()
時不應該被轉義的字符,它不會影響寫入sys.stdout
或sys.stderr
)。
str.isspace()
如果字符串中只有空格字符,并且至少有一個字符,則返回true,否則返回false??崭褡址窃赨nicode字符數據庫中定義為“Other”或“Separator”的那些字符,以及具有“WS”,“B”或“S”之一的雙向屬性的那些字符。
str.istitle()
如果字符串是一個標題字符串,并且至少有一個字符,則返回true,例如,大寫字符只能跟在uncased字符之后,而小寫字符只能在一個cased字符之后。否則返回false。
str.isupper()
如果字符串中的所有cased字符都是大寫且至少有一個cased字符,則返回true,否則返回false。
str.join(iterable)
返回一個字符串,它是iterable中字符串的串聯。如果
iterable中有任何非字符串值,包括
bytes對象,則會引發
TypeError`。元素之間的分隔符是提供此方法的字符串。
str.ljust(width[, fillchar])
返回一個新的字符串。如果width<=len(str)
,則字符串不變,否則將字符串左對齊,并且在后面填充fillchar
(默認是ASCII的空格).
str.lower()
返回字符串的一個副本,并將所有字符轉換為小寫字母。
str.lstrip([chars])
返回刪除前導字符的字符串的副本。 chars
參數是一個字符串,指定要刪除的字符集。如果省略或者None
,chars
參數默認刪除空格。 chars
參數不是一個前綴;相反,它的值的所有組合都被剝離了:
>>> ' spacious '.lstrip()
'spacious '
>>> 'www.example.com'.lstrip('cmowz.')
'example.com'
static str.maketrans(x[, y[, z]])
這個靜態方法返回一個可用于str.translate()
的轉換表
如果只有一個參數,它必須是一個將Unicode序數(整數)或字符(長度為1的字符串)映射到Unicode序號,字符串(任意長度)或None
的字典。字符鍵將被轉換為序號。
如果有兩個參數,它們必須是長度相等的字符串,并且在結果字典中,x
中的每個字符將映射到y
中相同位置的字符。
如果有第三個參數,它必須是一個字符串,其字符將被映射到結果中的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
的第一個出現處拆分字符串,并返回包含分隔符之前的部分,分隔符本身和分隔符之后的部分的三元組。如果找不到分隔符,則返回包含字符串本身及兩個空字符串的三元組。
>>>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])返回所有出現的子字符串
old替換為
new的字符串的副本。如果給出可選參數
count,則只會替換
count`次數。
>>>l = 'youyouyouyou'
>>>l.replace('y', 'r', 2)
'rourouyouyou'
str.rfind(sub[, start[, end]])
返回找到substring sub
的字符串中的最高索引,使得sub
包含在s [start:end]
內??蛇x參數start
和end
被解釋為切片符號。當失敗時返回-1
。
對比find
方法,此方法為從后往前查找(rfind-->right find)
str.rindex(sub[, start[, end]])
和rfind()
一樣,但是在找不到子字符串sub
時引發ValueError
。
對比index
方法,此方法為從后往前查找(rindex-->right index)
str.rjust(width[, fillchar])
返回字符串右對齊的長度為width
的字符串。填充是使用指定的fillchar
(默認是ASCII中的空格)完成的。如果width
小于或等于len(s)
,則返回原始字符串。
對比ljust
方法,此方法為右對齊。
str.rpartition(sep)
在sep
的最后出現處拆分字符串,并返回包含分隔符之前的部分,分隔符本身和分隔符之后的部分的三元組。如果未找到分隔符,則返回包含兩個空字符串的三元組,然后返回字符串本身。
對比partition
方法,rpartition從右到左遍歷。
str.rsplit(sep=None, maxsplit=-1)
返回字符串中的單詞列表,使用sep
作為分隔符字符串。如果給出maxsplit
,最多分割maxsplit
次,此方法從最右邊開始分割。如果sep沒有指定或者沒有,則任何空格字符串都是分隔符。除了從右邊分割外,[rsplit()
]的行為就像[split()
],這在下面詳細描述。
str.rstrip([chars])
返回刪除了尾隨字符的字符串的副本。 chars
參數是一個字符串,指定要刪除的字符集。如果省略或者None
,chars
參數默認刪除空格。 chars
參數不是后綴;相反,其值的所有組合都被剝離:
>>> ' spacious '.rstrip()
' spacious'
>>> 'mississippi'.rstrip('ipz')
'mississ'
str.split(sep=None, maxsplit=-1)
返回字符串中的單詞列表,使用sep作為分隔符字符串。如果給出maxsplit
,最多分割maxsplit
次(因此,該列表最多只有maxsplit + 1
個元素)。如果maxsplit沒有被指定或者是-1
,那么分割的數量是沒有限制的(返回所有可能的分割)。
如果給定sep
,則分割時連續的分隔符不會被分組在一起,并被視為分隔空字符串(例如'1,2'.split(',')
返回['1','','' 2' ]
)。 sep
參數可以由多個字符組成(例如,'1<>2<>3'.split('<>')
返回['1','2','3']
) 。用指定的分隔符分割空字符串會返回['']
。
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,則應用不同的分割算法:將連續空白的運行視為單個分隔符,并且如果該字符串具有前導或結果,則在開始或結束時不會包含空字符串或拖尾的空白。因此,將一個空字符串或一個只包含空格的字符串與一個“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])
返回字符串中lines的列表,在lines邊界處突破。換行符不包含在結果列表中,除非* 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()
]不同,此方法返回空字符串的空列表,并且終端行分隔不會導致多余行:
>>>"".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也可以是一個前綴元組來查找。使用可選的start
,測試字符串從該位置開始。使用可選的end
,停止在該位置比較字符串。
類比endswith.
str.strip([chars])
返回刪除前導字符和尾隨字符的字符串副本。 * chars 參數是一個字符串,指定要刪除的字符集。如果省略或者None
, chars *參數默認刪除空格。 * chars *參數不是前綴或后綴;相反,其值的所有組合都被剝離:
>>>' spacious '.strip()
'spacious'
>>> 'www.example.com'.strip('cmowz.')
'example'
從字符串中剝離最外部的前導和尾部chars
參數值。從前端刪除字符,直到到達chars
中字符集中不包含的字符串字符。尾端發生類似的行為。例如:
>>>comment_string = '#....... Section 3.2.1 Issue #32 .......'
>>> comment_string.strip('.#! ')
'Section 3.2.1 Issue #32'
str.swapcase()
返回大寫字符轉換為小寫字符串的副本,反之亦然。請注意,s.swapcase().swapcase()== s
不一定成立。
str.title()
返回字符串的字幕版本,其中字以大寫字符開頭,其余字符為小寫字母。
For example:
>>> 'Hello world'.title()
'Hello World'
該算法使用簡單的與語言無關的單詞定義作為連續字母組。這個定義在很多情況下都有效,但是這意味著收縮和占有者的撇號(')形成了單詞邊界,這可能不是理想的結果:
>>>"they're bill's friends from the UK".title()
"They'Re Bill'S Friends From The Uk"
可以使用正則表達式構造撇號的解決方法:
>>> 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)
通過給定的轉換表返回每個字符已映射的字符串的副本。該表必須是通過__getitem __()
實現索引的對象,通常是mapping
或sequence
。當通過Unicode序數(整數)索引時,表對象可以執行以下任何操作:返回Unicode序號或字符串,將字符映射到一個或多個其他字符;返回None
,從返回字符串中刪除字符;或引發LookupError
異常,將字符映射到自身。
你可以使用[str.maketrans()
]來創建不同格式的字符到字符映射的轉換映射。
另請參閱codecs
模塊,以獲得更靈活的自定義字符映射方法。
str.upper()
返回字符串的所有字符轉換為大寫的副本。請注意,如果s
包含uncased字符,或者如果生成的字符的Unicode類別不是“Lu”(Letter,大寫),則str.upper().isupper()
可能是False
。比如: “Lt”(Letter,titlecase)。
Unicode標準的第3.13節描述了The uppercasing algorithm
.
str.zfill(width)
返回一個左邊填充了ASCII0
數字的字符串的副本,以產生一個長度為width
的字符串。 前導符號前綴('+'
/`` - ')是通過在符號字符之后插入填充符*而不是之前處理的。 如果
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.
這里描述的格式化操作表現出各種各樣的怪癖,導致許多常見錯誤(如未能正確顯示元組和字典)。使用新的formatted string literals
或str.format()
接口有助于避免這些錯誤。這些替代方案還提供了更強大,靈活和可擴展的方法來格式化文本。
字符串對象有一個獨特的內置操作:%
操作符(模)。這也被稱為字符串* formatting 或 interpolation 運算符。給定format%values
(其中 format 是一個字符串), format 中的%
轉換規范被替換為 values *的零個或多個元素。其效果與在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常規類別 | |
---|---|
類別 | 說明 |
Lu | 字母,大寫 |
Ll | 字母,小寫 |
Lt | 字母,詞首字母大寫 |
Lm | 字母,修飾符 |
Lo | 字母,其他 |
Mn | 標記,非間距 |
Mc | 標記,間距組合 |
Me | 標記,封閉 |
Nd | 數字,十進制數 |
Nl | 數字,字母 |
No | 數字,其他 |
Pc | 標點,連接符 |
Pd | 標點,短劃線 |
Ps | 標點,開始 |
Pe | 標點,結束 |
Pi | 標點,前引號(根據用途可能表現為類似 Ps 或 Pe) |
Pf | 標點,后引號(根據用途可能表現為類似 Ps 或 Pe) |
Po | 標點,其他 |
Sm | 符號,數學 |
Sc | 符號,貨幣 |
Sk | 符號,修飾符 |
So | 符號,其他 |
Zs | 分隔符,空白 |
Zl | 分隔符,行 |
Zp | 分隔符,段落 |
Cc | 其他,控制 |
Cf | 其他,格式 |
Cs | 其他,代理項 |
Co | 其他,私用 |
Cn | 其他,未賦值(不存在任何字符具有此屬性) |