python3 标准库——string

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()捕捉到错误,把它依旧留在文本中。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值