字符串不僅支持所有通用序列操作,還實現(xiàn)了很多附件方法。
我會以『字符串方法』為標題,分幾篇筆記逐一介紹這些方法。
我會在這倉庫中持續(xù)更新筆記:https://github.com/orca-j35/python_notes
expandtabs
?? str.expandtabs(tabsize=8)
Return a copy of the string where all tab characters are replaced by one or more spaces, depending on the current column and the given tab size. Tab positions occur every tabsize characters (default is 8, giving tab positions at columns 0, 8, 16 and so on). To expand the string, the current column is set to zero and the string is examined character by character. If the character is a tab (\t), one or more space characters are inserted in the result until the current column is equal to the next tab position. (The tab character itself is not copied.) If the character is a newline (\n) or return (\r), it is copied and the current column is reset to zero. Any other character is copied unchanged and the current column is incremented by one regardless of how the character is represented when printed.
# 將字符串中的所有制表符替換空格,空格的數(shù)量取決于當前列的字符數(shù)和tablesize
# tabsize用于指定列寬,每列的寬度需等于tabsize,
# 若當前列的實際寬度<tabsize,剩余部分用0填充;
# 若當前列的實際長度≥tabsize,則將則當前列的寬度增加至tabsize的倍數(shù),剩余部分用0填充
# 比如'01\t012\t0123\t01234',有4列:01/012/0123/01234
'01\t012\t0123\t01234'.expandtabs()
# '01 012 0123 01234'
# '01234567012345670123456701234567'每列的寬度是8
'01\t012\t0123\t01234'.expandtabs(4)
# '01 012 0123 01234'
# '012301230123012301230123'每列的寬度是4
# 如果遇到'\n'或'\r',則會重新計算列寬
'01\t012\t0123\n01\t01234'.expandtabs()
# '01 012 0123\n01 01234'
# '01234567012345670123450123456701234567'每列的寬度是8
center
?? str.center(width[, fillchar])
Return centered in a string of length width. Padding is done using the specified fillchar(default is an ASCII space). The original string is returned if width is less than or equal to len(s).
# 以指定寬度width,對字符串進行居中
>>> 'orca_j35'.center(20)
' orca_j35 '
# fillchar用于指定填充字符,默認是ASCII空格
>>> 'orca_j35'.center(20,'*')
'******orca_j35******'
# 如果width≤len(s),則返回原字符串
>>> 'orca_j35'.center(1)
'orca_j35'
ljust
?? str.ljust(width[, fillchar])
Return the string left justified in a string of length width. Padding is done using the specified fillchar (default is an ASCII space). The original string is returned if width is less than or equal to len(s).
# 以指定寬度width,對字符串進行左對齊
>>> 'orca_j35'.ljust(20)
'orca_j35 '
# fillchar用于指定填充字符,默認是ASCII空格
>>> 'orca_j35'.ljust(20,'*')
'orca_j35************'
# 如果width≤len(s),則返回原字符串
>>> 'orca_j35'.ljust(1)
'orca_j35'
rjust
?? str.rjust(width[, fillchar])
Return the string right justified in a string of length width. Padding is done using the specified fillchar (default is an ASCII space). The original string is returned if width is less than or equal to len(s).
# 以指定寬度width,對字符串進行右對齊
>>> 'orca_j35'.rjust(20)
' orca_j35'
# fillchar用于指定填充字符,默認是ASCII空格
>>> 'orca_j35'.rjust(20,'*')
'************orca_j35'
# 如果width≤len(s),則返回原字符串
>>> 'orca_j35'.rjust(1)
'orca_j35'
zfill
?? str.zfill(width)
Return a copy of the string left filled with ASCII '0' digits to make a string of length width. A leading sign prefix ('+'/'-') is handled by inserting the padding after the sign character rather than before. The original string is returned if width is less than or equal to len(s).
For example:
# 在字符串左側填充'0',直至字符串的長度為width
>>> "42".zfill(5)
'00042'
# '+'/'-'會在'0'之前
>>> "-42".zfill(5)
'-0042'
>>> "+42".zfill(5)
'+0042'
>>> '--'.zfill(5)
'-000-'
>>> ' '.zfill(5)
'0000 '
>>> ''.zfill(5)
'00000'
# 其余符號會在'0'之后
>>> "=42".zfill(5)
'00=42'
# 如果width≤len(s),則返回原字符串
>>> 'orca_j35'.zfill(5)
'orca_j35'
format
?? str.format(*args, **kwargs)
str.format()和string.Formatter類均采用格式化字符串語法(Format String Syntax),該該語法和 f-string 的語法相似,但存在一些區(qū)別。有關格式化字符串語法的詳細信息可閱讀『string — Common string operations.md』。f-string、
string .format()、string.Formatter使用相同的格式化說明符(format specifier mini-language),詳見筆記『string — Common string operations.md』-> "Format Specification Mini-Language"。
該方法用于執(zhí)行字符串格式化操作,字符串對象中需包含:文本字面值和替換字段。替換字段是指被置于花括弧(curly braces) {} 中的表達式,其中可包含位置實參的數(shù)值索引,或包含關鍵字實參的名稱。str.format 方法會基于當前字符串創(chuàng)建一個新副本,并用實參替換掉副本中對應的字段。
>>> "The sum of 1 + 2 is {0}".format(1+2)
'The sum of 1 + 2 is 3'
有關格式化字符串的詳細語法,請閱讀 Format String Syntax;str.format 與 string.Formatter 擁有相同的實現(xiàn)方式,如果想了解 str.format 的實現(xiàn)方式 ,可以參考『string — Common string operations.md』-> "Custom String Formatting"。
Note - When formatting a number (
int,float,complex,decimal.Decimaland subclasses) with thentype (ex:'{:n}'.format(1234)), the function temporarily sets theLC_CTYPElocale to theLC_NUMERIClocale to decodedecimal_pointandthousands_sepfields oflocaleconv()if they are non-ASCII or longer than 1 byte, and theLC_NUMERIClocale is different than theLC_CTYPElocale. This temporary change affects other threads.
Changed in version 3.7: When formatting a number with the n type, the function sets temporarily the LC_CTYPE locale to the LC_NUMERIC locale in some cases.
format_map
?? str.format_map(mapping)
Similar to str.format(**mapping), except that mapping is used directly and not copied to a dict. This is useful if for example mapping is a dict subclass:
# 與str.format(**mapping)的區(qū)別在于無需對mapping進行解包
>>> student = dict(name='Joy',age=3)
>>> 'My name is {name},i am {age} old'.format_map(student)
'My name is Joy,i am 3 old'
>>> 'My name is {name},i am {age} old'.format(**student)
'My name is Joy,i am 3 old'
This is useful if for example mapping is a dict subclass:
>>> 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.