Python内置的string模块提供了一些有用的常量和方法用于操作文本。
常量
string模块中定义了一些常用的常量,例如小写字母,大写字母,阿拉伯数字等:
import string
for n in dir(string):
if n.startswith('_'):
continue
v = getattr(string, n)
if isinstance(v, basestring):
print '%s=%s' % (n, repr(v))
print
输出结果如下:
ascii_letters='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
ascii_lowercase='abcdefghijklmnopqrstuvwxyz'
ascii_uppercase='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
digits='0123456789'
hexdigits='0123456789abcdefABCDEF'
letters='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
lowercase='abcdefghijklmnopqrstuvwxyz'
octdigits='01234567'
printable='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'
punctuation='!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
uppercase='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
whitespace='\t\n\x0b\x0c\r '
函数
**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.
**translate() **
用于转换字符。
import string
leet = string.maketrans('abegiloprstz', '463611092572')
s = 'The quick brown fox jumped over the lazy dog.'
print s
print s.translate(leet)
输出结果如下:
The quick brown fox jumped over the lazy dog.
Th3 qu1ck 620wn f0x jum93d 0v32 7h3 142y d06.
Templates
Templates用于实现内置的插值操作,使用$var替换变量var。
import string
values = { 'var':'foo' }
t = string.Template("""
$var
$$
${var}iable
""")
print 'TEMPLATE:', t.substitute(values)
s = """
%(var)s
%%
%(var)siable
"""
print 'INTERPLOATION:', s % values
输出结果如下:
TEMPLATE:
foo
$
fooiable
INTERPLOATION:
foo
%
fooiable
如果字符串模板中的变量没有提供值,会抛出异常,这时,可以使用safe_substitute().
网友评论