String模块起源于Python最早的版本。以前在这模块实现的很多函数已经被转移到str对象方法中。string模块任然保留了几种有用的常量和类,本文主要来讨论它们。
Functions
函数capwords()将字符串中所有单词首字母大写。
In [1]: import string
In [2]: s = 'The quick brown fox jumped over the lazy dog.'
In [3]: print(s)
The quick brown fox jumped over the lazy dog.
In [4]: print(string.capwords(s))
The Quick Brown Fox Jumped Over The Lazy Dog.
结果相当于split(), 大写首字母然后join().
Templates
字符串格式化的几种用法:
In [5]: values = {'var': 'foo'}
In [6]: t = string.Template("""
...: Variable : $var
...: Escape : $$
...: Variable in text: ${var}iable
...: """)
In [7]: print('TEMPLATE:', t.substitute(values))
TEMPLATE:
Variable : foo
Escape : $
Variable in text: fooiable
In [8]: s = """
...: Variable : %(var)s
...: Escape : %%
...: Variable in text: %(var)siable
...: """
In [9]: print('INTERPOLATION:', s % values)
INTERPOLATION:
Variable : foo
Escape : %
Variable in text: fooiable
In [10]: s = """
...: Variable : {var}
...: Escape : {{}}
...: Variable in text: {var}iable
...: """
In [11]: print('FORMAT:', s.format(**values))
FORMAT:
Variable : foo
Escape : {}
Variable in text: fooiable
对于string.Template,如果有字符串没有提供在参数里,应用safe_substitute():
In [12]: t = string.Template("$var is here but $missing is not provided")
In [13]: try:
...: print('substitute() :', t.substitute(values))
...: except KeyError as err:
...: print('ERROR:', str(err))
...:
ERROR: 'missing'
In [14]: print('safe_substitute():', t.safe_substitute(values))
safe_substitute(): foo is here but $missing is not provided
由于没有与missing对应的值在字典中,substitute()函数引发KeyError, 而safe_substitute()捕捉到错误,把它依旧留在文本中。