天天看點

python string子產品學習

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().