《Python3-标准库》讲解

一、string:文本常量和模板
 函数: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.
--------------------------------------------------
这个代码的结果等同于先调用split(),把结果列表中的单词首字母大写,然后调用join()来合并结果.
--------------------------------------------------
字符串模板,将作为内置拼接语法的替代做法.
   代码清单
--------------------------------------------------
import string
values = {'var': 'foo'}
t = string.Template("""
Variable         : $var
Escape           : $$
Variable in text : ${var}iable
""")
print('TEMPLATE:', t.substitute(values))
s = """
Variable         : $(var)s
Escape           : $$
Variable in text : ${var}iable
"""
print('INTERPOLATION:', s % values)
s = """
Variable         : {var}
Escape           : {{}}
Variable in text : ${var}iable
"""
print('FORMAT:', s.format(**values))
----------------------------------------------------
结果
----------------------------------------------------
TEMPLATE:
Variable         : foo
Escape           : $
Variable in text : fooiable
INTERPOLATION:
Variable         : $(var)s
Escape           : $$
Variable in text : ${var}iable

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))
----------------------------------------------------
高级模板
----------------------------------------------------
delimiter和idpattern类属性。
----------------------------------------------------
代码清单
----------------------------------------------------
import string
class MyTemplate(string.Template):
    delimiter = '%'
    idpattern = '[a-z]+_[a-z]+'
   
template_text = '''
    Delimiter : %%
    Replaced  : %with_underscore
    Ignored   : %notunderscored
'''
d = {
    'with_underscore': 'replaced',
    'notunderscored': 'not replaced',
}
t = MyTemplate(template_text)
print('Modified ID pattern:')
print(t.safe_substitute(d))
-----------------------------------------------------
 
 
 
 
 
 
 
 
 
 
 
 
 
posted @ 2019-10-11 17:17  zhouhaiwu  阅读(270)  评论(0编辑  收藏  举报