string模块

string 模块保留的一些用来处理 str 对象的常量和类

string.capwords()  字符串的所有单词首字大写

import string

s = 'When the cat is away, the mice will play.'

print(s.title())            # 字符串的所有单词首字母大写
print(string.capwords(s))   # 字符串的所有单词首字母大写
print(' '.join([i.capitalize() for i in s.split(' ')]))   # split()返回的列表每个单词的首字母大写再join
# When The Cat Is Away, The Mice Will Play.
# When The Cat Is Away, The Mice Will Play.
# When The Cat Is Away, The Mice Will Play.

模板

定义模板

使用 safe_substitute() 方法可以带来一个好处,那就是如果模板需要的值没有全部作为参数提供给模板的话可以避免发生异常。

import string
value = {'var':'foo'}

t = string.Template('''
Variable        :$var
Escape          :$$
Variable in text:${var}
''')
print('TEAMPLATE:',t.substitute(value))

'''
TEAMPLATE: 
Variable        :foo
Escape          :$
Variable in text:foo
'''
value = {'var':'foo'}
s = """
Variable        : %(var)s
Escape          : %%
Variable in text: %(var)siable
"""

print('INTERPOLATION:', s % value)

'''
INTERPOLATION: 
Variable        : foo
Escape          : %
Variable in text: fooiable
'''
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
'''
原文地址:https://www.cnblogs.com/st-st/p/9677547.html