Python标准库(1)——string

1 字符串部分
1.1 string 包含常量及文字处理类
1.1.1 函数


capwords()函数将字符串中的每一个单词的首字母大写
>>> print string.capwords('my name is lxg')
My Name Is Lxg
该函数的功能类似于调用字符串的split()函数,将每个单词首字母大写,然后调用join
()方法将单词拼接起来
>>> print ' '.join([s.capitalize() for s in 'my name is lxg'.split()])
My Name Is Lxg
与str.capitalize()函数不同,str.capitalize()函数只将字符串的第一个单词的首字母大写
>>> print 'my name is lxg'.capitalize()
My name is lxg


maketrans()函数可以创建一个转换表,然后调用str.translate()方法可以使用该转换表
>>> table = string.maketrans('abcdefg', '1234567')
>>> 'my name is lxg'.translate(table)
'my n1m5 is lx7'
从输出可以看出,字母a转换成1,字母e转换成5, 字母g转换成7


1.1.2 Templates
string.Template可以对字符串中的命名参数进行变量替换
>>> template = string.Template('my name is ${name}')
>>> template.substitute({'name':'lxg'})
'my name is lxg'
从输出可以看出,模板中的name变量被替换成了lxg


1.3 re 正则表达式库,用于正则表达式的模式匹配和查找
1.3.1 模式查找。最常用的方式是在一段文本中查找特定的模式。search(pattern, text)接受两个参数。如果模式匹配,则返回一个Match对象;否则返回None
每一个Match对象都包含了该模式匹配的一些基本信息,包括最初传入的字符串,使用的正则表达式,以及匹配的模式在字符串中的位置。
>>> import re
>>> pattern = 'lxg'
>>> text = 'my name is lxg'
>>> match = re.search(pattern, text)
>>> print 'Found "%s"\nin "%s"\nfrom %d to %d' % (match.re.pattern, match.string, match.start(), match.end())
Found "lxg"
in "my name is lxg"
from 11 to 14
1.3.2 编译正则表达式。compile()方法可以将一段正则表达式编译成一个RegexObject对象
>>> regex = re.compile('lxg')
>>> match = regex.search('my name is lxg')
>>> print 'Found "%s"\nin "%s"' % (match.re.pattern, match.string)
Found "lxg"
in "my name is lxg"
1.3.3 多结果匹配。findall()方法可以返回所有的匹配结果。finditer()方法也可以返回所有的匹配结果,区别是结果为Match对象,而不是string
>>> for match in re.findall('lxg', 'my name is lxg and lxg is my name'):
...     print 'found %s' % match
...
found lxg
found lxg


>>> for match in re.finditer('lxg', 'my name is lxg and lxg is my name'):
...     print 'found at %d-%d' % (match.start(), match.end())
...
found at 11-14
found at 19-22

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值