String模块包含大量实用常量和类,以及一些过时的遗留功能,并还可用作字符串操作。
1.常用方法
ps:原谅我太懒了 只能从公众号截图了求点击,求关注
2.字符串常量
3.字符串模板Template
通过string.Template可以为Python定制字符串的替换标准,下面是具体列子:
Template还有更加高级的用法,可以通过继承string.Template, 重写变量delimiter(定界符)和idpattern(替换格式), 定制不同形式的模板。
输出:
Delimiter : not replaced Replaced : %with_underscore Ingored : %notunderscored
Delimiter : $de Replaced : replaced Ingored : %notunderscored
4.常用字符串技巧a.字符串反转
>>> s = '1234567890'
>>> print s[::-1]
0987654321
b.关于字符串链接
尽量使用join()链接字符串,因为’+’号连接n个字符串需要申请n-1次内存,使用join()需要申请1次内存。
c.固定长度分割字符串
>>> import re
>>> s = '1234567890'
>>> re.findall(r'.{1,3}', s) # 已三个长度分割字符串
['123', '456', '789', '0']
d.使用()括号生成字符串
sql = ('SELECT count() FROM table '
'WHERE id = "10" '
'GROUP BY sex')
print sql
SELECT count() FROM table WHERE id = "10" GROUP BY sex
e.将print的字符串写到文件
>>> print >> open("somefile.txt", "w+"), "Hello World" # Hello World将写入文件somefile.txt