前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python string模块学习

python string模块学习

作者头像
用户2936342
发布2018-08-27 15:01:16
2070
发布2018-08-27 15:01:16
举报
文章被收录于专栏:nummynummy

Python内置的string模块提供了一些有用的常量和方法用于操作文本。

常量

string模块中定义了一些常用的常量,例如小写字母,大写字母,阿拉伯数字等:

代码语言:javascript
复制
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

输出结果如下:

代码语言:javascript
复制
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() ** 用于将字符串中每个单词首字母改为大写。

代码语言:javascript
复制
import string

s = 'The quick brown fox jumped over the lazy dog.'

print s
print string.capwords(s)

输出结果如下:

代码语言:javascript
复制
The quick brown fox jumped over the lazy dog.
The Quick Brown Fox Jumped Over The Lazy Dog.

**translate() ** 用于转换字符。

代码语言:javascript
复制
import string

leet = string.maketrans('abegiloprstz', '463611092572')

s = 'The quick brown fox jumped over the lazy dog.'

print s
print s.translate(leet)

输出结果如下:

代码语言:javascript
复制
The quick brown fox jumped over the lazy dog.
Th3 qu1ck 620wn f0x jum93d 0v32 7h3 142y d06.

Templates

Templates用于实现内置的插值操作,使用$var替换变量var。

代码语言:javascript
复制
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

输出结果如下:

代码语言:javascript
复制
TEMPLATE:
foo
$
fooiable

INTERPLOATION:
foo
%
fooiable

如果字符串模板中的变量没有提供值,会抛出异常,这时,可以使用safe_substitute().

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017.03.11 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 常量
  • 函数
  • Templates
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档