python字符串库函数_Python标准库概览(1):string
Python的 string 標準庫保留了一些有用的函數和用于處理文本對象的類,現在我們來一起看一下Python的string標準庫還有哪些我們不知道的有趣用法?
01、capwords()函數:將字符串中的所有單詞大寫
import string
s = 'The quick brown fox jumped over the lazy dog.'
print(s)
print(string.capwords(s))
輸出:
The quick brown fox jumped over the lazy dog.
The Quick Brown Fox Jumped Over The Lazy Dog.
02、字符串模板
使用string.Template插值時,通過在名稱前加上
var)來標識變量。另外,如果有必要將其與周圍的文本區分開,還可以用花括號將它們包裹起來(例如${var})
使用$插值標記
import string
values = {'var': 'foo'}
t = string.Template("""Variable : $varEscape : $$Variable in text: ${var}iable""")
print('TEMPLATE:', t.substitute(values))
輸出:
TEMPLATE:
Variable : foo
Escape : $
Variable in text: fooiable
使用%插值標記
import string
values = {'var': 'foo'}
s = """Variable :%(var)sEscape :%%Variable in text:%(var)siable"""
print('INTERPOLATION:', s % values)
輸出:
INTERPOLATION:
Variable : foo
Escape : %
Variable in text: fooiable
使用{}插值標記
import string
values = {'var': 'foo'}
s = """Variable : {var}Escape : {{}}Variable in text: {var}iable"""
print('FORMAT:', s.format(**values))
輸出:
FORMAT:
Variable : foo
Escape : {}
Variable in text: fooiable
模板和字符串插值或格式之間的一個關鍵區別是不用考慮參數的類型。將值轉換為字符串,然后將字符串插入結果中。例如,無法控制用于表示浮點值的位數 但是,這樣做的好處是,safe_substitute() 如果未將模板所需的所有值都作為參數提供,則使用該方法可以避免出現異常。
import string
values = {'var': 'foo'}
t = string.Template("$var is here but $missing is not provided")
try:
print('substitute() :', t.substitute(values))
except KeyError as err:
print('ERROR:', str(err))
print('safe_substitute():', t.safe_substitute(values))
輸出:
ERROR: 'missing'
safe_substitute(): foo is here but $missing is not provided
03、高級文本模板
string.Template可以通過調整用于在模板主體中查找變量名稱的正則表達式模式來更改其默認語法。例如更改類的delimiter和idpattern屬性
import string
class MyTemplate(string.Template):
delimiter = '%'
idpattern = '[a-z]+_[a-z]+'
template_text = '''Delimiter :%%Replaced : %with_underscoreIgnored : %notunderscored'''
d = {
'with_underscore': 'replaced',
'notunderscored': 'not replaced',
}
t = MyTemplate(template_text)
print('Modified ID pattern:')
print(t.safe_substitute(d))
輸出:
Modified ID pattern:
Delimiter : %
Replaced : replaced
Ignored : %notunderscored
04、標準庫文本常量
string模塊包括許多與ASCII和數字字符集有關的常量,這些常量在處理ASCII數據時很有用
import inspect
import string
def is_str(value):
return isinstance(value, str)
for name, value in inspect.getmembers(string, is_str):
if name.startswith('_'):
continue
print('%s=%r\n' % (name, value))
輸出:
ascii_letters='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
ascii_lowercase='abcdefghijklmnopqrstuvwxyz'
ascii_uppercase='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
digits='0123456789'
hexdigits='0123456789abcdefABCDEF'
octdigits='01234567'
printable='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~\t\n\r\x0b\x0c'
punctuation='!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
whitespace='\t\n\r\x0b\x0c'
今天和大家一起學習了Python中的標準庫 string,大家都學會了嗎? 歡迎大家關注,一起學習Python吧!
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的python字符串库函数_Python标准库概览(1):string的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql 按照in id顺序_Mysq
- 下一篇: python把一堆图片分成n份,用Pyt