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吧!