Python Standard Library based on Python 3.7.3 https://docs.python.org/3/library/
Python標(biāo)準(zhǔn)庫(kù) - 文本處理服務(wù) - string庫(kù)
Source code: Lib/string.py
Link: https://docs.python.org/3/library/string.html#module-string
目錄鏈接:http://www.reibang.com/p/e1e201bea601
字符串常量 String constants :
GitHub Code : String constants.py
string.ascii_letters 大小寫(xiě)字母常數(shù)
# ascii_letters 大小寫(xiě)字母常數(shù)
print(string.ascii_letters) # abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
string.ascii_lowercase 小寫(xiě)字母常數(shù)
# ascii_lowercase 小寫(xiě)字母常數(shù)
print(string.ascii_lowercase) # abcdefghijklmnopqrstuvwxyz
string.ascii_uppercase 大寫(xiě)字母常數(shù)
# ascii_uppercase 大寫(xiě)字母常數(shù)
print(string.ascii_uppercase) # ABCDEFGHIJKLMNOPQRSTUVWXYZ
string.digits 十進(jìn)制數(shù)字常數(shù)
# digits 十進(jìn)制數(shù)字常數(shù)
print(string.digits) # 0123456789
string.hexdigits 十六進(jìn)制數(shù)字常數(shù)
# hexdigits 十六進(jìn)制數(shù)字常數(shù)
print(string.hexdigits) # 0123456789abcdefABCDEF
string.octdigits 八進(jìn)制數(shù)字常數(shù)
# octdigits 八進(jìn)制數(shù)字常數(shù)
print(string.octdigits) # 01234567
string.punctuation ASCII字符串填具,在C語(yǔ)言環(huán)境中被視為標(biāo)點(diǎn)字符
# punctuation ASCII字符串蛾默,在C語(yǔ)言環(huán)境中被視為標(biāo)點(diǎn)字符
print(string.punctuation) # !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
string.printable 能夠被打印的ASCII字符串
# printable 能夠被打印的ASCII字符串
print(string.printable)
# 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ 還要加上 字符空間,制表符喻旷,換行符酌摇,返回頁(yè)面,換頁(yè)符和垂直選項(xiàng)卡
string.whitespace 字符空間雀鹃,制表符舷暮,換行符,返回頁(yè)面帕涌,換頁(yè)符和垂直選項(xiàng)卡
# whitespace 包含所有被視為空格的ASCII字符的字符串
print(string.whitespace) # 字符空間摄凡,制表符续徽,換行符,返回頁(yè)面亲澡,換頁(yè)符和垂直選項(xiàng)卡
自定義字符串格式 Custom String Formatting
GitHub Code : Custom String Formatting.py
介紹自定義字符串格式 class string.Formatter中主要的3個(gè)函數(shù)
format(format_string, *args, **kwargs)钦扭、vformat(format_string, args, kwargs)、parse(format_string)
format(format_string, *args, **kwargs)
主要的API方法床绪。它采用格式字符串和一組任意位置和關(guān)鍵字參數(shù)土全。它只是一個(gè)調(diào)用vformat()的包裝器。
'''
@Description: 主要的API方法会涎。它采用格式字符串和一組任意位置和關(guān)鍵字參數(shù)。它只是一個(gè)調(diào)用vformat()的包裝器瑞凑。
@Param:
format_string: 需要去格式化的目標(biāo)字符串
*args: 任意位置 元組
**kwargs: 關(guān)鍵字參數(shù) 字典
@Return:
'''
# string.Formatter.format(format_string, *args, **kwargs)
data = ("Pi = ",3.1415926)
strtmp = "This is a test:{}{:.4f}"
formatter = string.Formatter()
strtmp = formatter.format(strtmp,*data) # 元組
print(strtmp) # This is a test:Pi = 3.1416
data = {"Key1":3.1415926,"Key2":"Pi = "}
strtmp = "This is a test:{Key2}{Key1}"
formatter = string.Formatter()
strtmp = formatter.format(strtmp,**data) # 字典
print(strtmp) # This is a test:Pi = 3.1415926
# string.Formatter.format(format_string, *args, **kwargs) End
vformat(format_string, args, kwargs)
此函數(shù)執(zhí)行格式化的實(shí)際工作
'''
@Description: 此函數(shù)執(zhí)行格式化的實(shí)際工作
@Param:
format_string: 需要去格式化的目標(biāo)字符串
args: 任意位置 元組
kwargs: 關(guān)鍵字參數(shù) 字典
@Return:
'''
# string.Formatter.vformat(format_string, args, kwargs)
# 注意 Formatter.vformat的參數(shù)不是 (*args, **kwargs) 而是 (args, kwargs)
data = ("Pi = ",3.1415926)
strtmp = "This is a test:{}{:.4f}"
formatter = string.Formatter()
strtmp = formatter.vformat(strtmp,data,{}) # 元組
print(strtmp) # This is a test:Pi = 3.1416
data = {"Key1":3.1415926,"Key2":"Pi = "}
strtmp = "This is a test:{Key2}{Key1}"
formatter = string.Formatter()
strtmp = formatter.vformat(strtmp,(),data) # 字典
print(strtmp) # This is a test:Pi = 3.1415926
# string.Formatter.vformat(format_string, args, kwargs) End
parse(format_string)
循環(huán)遍歷format_string并返回一個(gè)可迭代的元組(literal_text末秃,field_name,format_spec籽御,conversion)练慕。
'''
@Description: 循環(huán)遍歷format_string并返回一個(gè)可迭代的元組(literal_text,field_name技掏,format_spec铃将,conversion)。 vformat()使用它將字符串分解為文字文本或替換字段哑梳。
@Param:
format_string:需要去格式化的目標(biāo)字符串
@Return:
tuples 元組
'''
# string.Formatter.parse(format_string)
strtmp = "This is a test:{}{:.4f}"
formatter = string.Formatter()
strtuple = formatter.parse(strtmp)
for i, v in enumerate(strtuple):
print(i, v)
'''
0 ('This is a test:', '', '', None)
1 ('', '', '.4f', None)
'''
strtmp = "This is a test:{Key2}{Key1}"
formatter = string.Formatter()
strtuple = formatter.parse(strtmp)
for i, v in enumerate(strtuple):
print(i, v)
'''
0 ('This is a test:', 'Key2', '', None)
1 ('', 'Key1', '', None)
'''
# string.Formatter.parse(format_string) End
格式字符串語(yǔ)法示例 Format String Syntax examples
GitHub Code : Format String Syntax.py
包含str.format()語(yǔ)法的示例以及與舊的%-formatting的比較劲阎。
在大多數(shù)情況下,語(yǔ)法類似于舊的%-formatting鸠真,添加了{(lán)}和with:而不是%悯仙。例如,'%03.2f'可以翻譯為'{:03.2f}'吠卷。
Accessing arguments by position: 按位置訪問(wèn)參數(shù):
tupdata = ("This","is","a","test") # 元組
formatstr = '{0} {1} {2} {3}'.format("This","is","a","test")
print(formatstr) # This is a test
formatstr = '{} {} {} {}'.format(*tupdata) # *data 解包參數(shù)序列
print(formatstr) # This is a test
formatstr = '{3} {2} {1} {0}'.format(*tupdata) # *data 解包參數(shù)序列
print(formatstr) # test a is This
formatstr = '{2} {3} {1} {2} {3}'.format(*tupdata) # 參數(shù)可以重復(fù)
print(formatstr) # a test is a test
Accessing arguments by name:按關(guān)鍵字訪問(wèn)參數(shù):
dicdata = {'Author':'leacoder','Time':'2019/04/17'}
formatstr = 'The author is {Author}锡垄,The time is {Time}'.format(Author='leacoder',Time='2019/04/17')
print(formatstr) # The author is leacoder,The time is 2019/04/17
formatstr = 'The author is {Author}祭隔,The time is {Time}'.format(**dicdata)
print(formatstr) # The author is leacoder货岭,The time is 2019/04/17
Accessing arguments’ attributes: 訪問(wèn)參數(shù)的屬性:
class Point:
def __init__(self,x,y):
self.x ,self.y = x, y
point = Point(4,2)
formatstr = 'Thie point is ({key.x},{key.y})'.format(key = point) # key 可為其他
print(formatstr) # Thie point is (4,2)
formatstr = 'Thie point is ({point.x},{point.y})'.format(point = point) # point 可為其他
print(formatstr) # Thie point is (4,2)
Accessing arguments’ items: 訪問(wèn)參數(shù)的各項(xiàng):
tupdata = ("leacoder","2019/04/17") # 元組
formatstr = 'The author is {0[0]},The time is {0[1]}'.format(tupdata)
print(formatstr) # The author is leacoder,The time is 2019/04/17
formatstr = 'The author is {0[0]},The time is {0[1]}'.format(*tupdata) # 注意區(qū)別
print(formatstr) # The author is l,The time is e
Replacing %s and %r: 替換%s和%r: 使用 !s !r
formatstr = "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2')
print(formatstr) # repr() shows quotes: 'test1'; str() doesn't: test2
Aligning the text and specifying a width: 對(duì)齊文本并指定寬度:
formatstr = '{:<30}'.format('left aligned') # 左對(duì)齊 30位
print(formatstr) # ‘left aligned ’ 為了體現(xiàn)位數(shù)加了‘’
formatstr = '{:>30}'.format('right aligned') # 右對(duì)齊 30位
print(formatstr) # ‘ right aligned’
formatstr = '{:^30}'.format('centered') # 中間對(duì)齊 30位
print(formatstr) # ‘ centered ’
formatstr = '{:*^30}'.format('centered') # 使用* 作為填充字符
print(formatstr) # ‘***********centered***********’
Replacing %+f, %-f, and % f and specifying a sign: 替換%+ f,% - f和%f并指定符號(hào):
formatstr = '{:+f}; {:+f}'.format(3.14, -3.14) # 總是顯示它符號(hào)
print(formatstr) # ‘+3.140000; -3.140000’
formatstr = '{: f}; {: f}'.format(3.14, -3.14) # 正數(shù)前顯示空格
print(formatstr) # ‘ 3.140000; -3.140000’
formatstr = '{:-f}; {:-f}'.format(3.14, -3.14) # 只顯示負(fù)號(hào) 同 '{:f}; {:f}'
print(formatstr) # ‘3.140000; -3.140000’
Replacing %x and %o and converting the value to different bases: 替換%x和%o并將值轉(zhuǎn)換為不同的進(jìn)制:
formatstr = "int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(64)
print(formatstr) # int: 64; hex: 40; oct: 100; bin: 1000000
formatstr = "int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(64)
print(formatstr) # int: 64; hex: 0x40; oct: 0o100; bin: 0b1000000
formatstr = "int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(0b1000001) # 也支持其他進(jìn)制
print(formatstr) # int: 65; hex: 0x41; oct: 0o101; bin: 0b1000001
Using the comma as a thousands separator: 使用逗號(hào)作為千位分隔符:
formatstr = '{:,}'.format(1234567890)
print(formatstr) # 1,234,567,890
Expressing a percentage: 表達(dá)百分比:
points = 1
total = 3
formatstr = 'points / total = {:.2%}'.format(points/total)
print(formatstr) # points / total = 33.33%
Using type-specific formatting: 使用特定類型的格式:
import datetime
d = datetime.datetime(2019, 4, 17, 22, 49, 2) # 2019/04/17 22:49:02
formatstr = '{:%Y-%m-%d %H:%M:%S}'.format(d)
print(formatstr) # 2019-04-17 22:49:02
模板字符串 Template strings
GitHub Code : Template strings.py
模板字符串的規(guī)則
'''
模板字符串提供更簡(jiǎn)單的字符串替換疾渴,如PEP 292中所述 https://www.python.org/dev/peps/pep-0292/
模板字符串支持基于$的替換千贯,使用以下規(guī)則:
1、$$是轉(zhuǎn)義; 它被替換為單個(gè)$程奠。
2丈牢、$identifier 一個(gè)替換占位符,用于匹配映射關(guān)鍵字“identifier”默認(rèn)情況下瞄沙,
“標(biāo)識(shí)符”僅限于以下劃線或ASCII字母開(kāi)頭的任何不區(qū)分大小寫(xiě)的ASCII字母數(shù)字字符串(包括下劃線)己沛。$字符后面的第一個(gè)非標(biāo)識(shí)符字符結(jié)束此占位符慌核。
3、$ {identifier}相當(dāng)于$ identifier申尼。當(dāng)有效標(biāo)識(shí)符字符跟隨占位符但不是占位符的一部分時(shí)垮卓,例如“$ {noun} ification”,則需要它师幕。
4粟按、字符串中$的任何其他形式都將導(dǎo)致引發(fā)ValueError。
字符串模塊提供實(shí)現(xiàn)這些規(guī)則的Template類霹粥。class string.Template(template)
'''
class string.Template 類
substitute(mapping, **kwds)
'''
@Description: 執(zhí)行模板替換灭将,返回一個(gè)新字符串。
@Param:
mapping:任何類似字典的對(duì)象后控,其鍵與模板中的占位符匹配庙曙。
**kewds: 關(guān)鍵字參數(shù),其中關(guān)鍵字是占位符浩淘。
當(dāng)給出mapping和kwds并且存在重復(fù)時(shí)捌朴,來(lái)自kwds的占位符優(yōu)先。
@Return: 返回一個(gè)新字符串
'''
# substitute(mapping, **kwds)
s = Template('The Author is $Author, The Time is $Time') # 使用Template類構(gòu)造函數(shù)
kewds = {'Author':'leacoder', 'Time':'2019/04/18 00:01:38'}
templatestr = s.substitute(Author='leacoder', Time='2019/04/18 00:01:38') # **kewds
print(templatestr) # The Author is leacoder, The Time is 2019/04/18 00:01:38
templatestr = s.substitute(**kewds) # **kewds
print(templatestr) # The Author is leacoder, The Time is 2019/04/18 00:01:38
templatestr = s.substitute(kewds) # mapping
print(templatestr) # The Author is leacoder, The Time is 2019/04/18 00:01:38
templatestr = s.substitute(kewds,Author='250',Time = 'No Time') # mapping **kewds
print(templatestr) # The Author is 250, The Time is No Time
kewds1 = {'Author':'leacoder'}
templatestr = s.substitute(kewds1)
print(templatestr) # KeyError: 'Time'
# substitute(mapping, **kwds) End
safe_substitute(mapping, **kwds)
'''
@Description:
與substitute()一樣张抄,如果map和kwds中缺少占位符砂蔽,原始占位符將在結(jié)果字符串中完整顯示,而不是引發(fā)KeyError異常
此外署惯,與substitute()不同左驾,$的任何其他形式只會(huì)返回$而不是引發(fā)ValueError。
@Param:
同 substitute()
@Return:
'''
# safe_substitute(mapping, **kwds)
kewds1 = {'Author':'leacoder'}
templatestr = s.safe_substitute(kewds1)
print(templatestr) # The Author is leacoder, The Time is $Time
# safe_substitute(mapping, **kwds) End
GitHub鏈接:
https://github.com/lichangke/LeetCode
知乎個(gè)人首頁(yè):
https://www.zhihu.com/people/lichangke/
簡(jiǎn)書(shū)個(gè)人首頁(yè):
http://www.reibang.com/u/3e95c7555dc7
個(gè)人Blog:
https://lichangke.github.io/
歡迎大家來(lái)一起交流學(xué)習(xí)