1. 经常使用方法python
2.字符串常量git
3.字符串模板Templategithub
经过string.Template能够为Python定制字符串的替换标准,下面是具体列子:sql
>>>from string import Template.net
>>>s = Template('$who like $what')blog
>>>print s.substitute(who='i', what='python')继承
i like python内存
>>>print s.safe_substitute(who='i') # 缺乏key时不会抛错字符串
i like $whatunderscore
>>>Template('${who}LikePython').substitute(who='I') # 在字符串内时使用{}
'ILikePython'
Template还有更加高级的用法,能够经过继承string.Template, 重写变量delimiter(定界符)和idpattern(替换格式), 定制不一样形式的模板。
import string
template_text = ''' Delimiter : $de Replaced : %with_underscore Ingored : %notunderscored '''
d = {'de': 'not replaced',
'with_underscore': 'replaced',
'notunderscored': 'not replaced'}
class MyTemplate(string.Template):
# 重写模板 定界符(delimiter)为"%", 替换模式(idpattern)必须包含下划线(_)
delimiter = '%'
idpattern = '[a-z]+_[a-z]+'
print string.Template(template_text).safe_substitute(d) # 采用原来的Template渲染
print MyTemplate(template_text).safe_substitute(d) # 使用重写后的MyTemplate渲染
输出:
Delimiter : not replaced
Replaced : %with_underscore
Ingored : %notunderscored
Delimiter : $de
Replaced : replaced
Ingored : %notunderscored
原生的Template只会渲染界定符为$的状况,重写后的MyTemplate会渲染界定符为%且替换格式带有下划线的状况。
4.经常使用字符串技巧
1.反转字符串
>>> s = '1234567890'
>>> print s[::-1]
0987654321
2.关于字符串连接
尽可能使用join()连接字符串,由于’+’号链接n个字符串须要申请n-1次内存,使用join()须要申请1次内存。
3.固定长度分割字符串
>>> import re
>>> s = '1234567890'
>>> re.findall(r'.{1,3}', s) # 已三个长度分割字符串
['123', '456', '789', '0']
4.使用()括号生成字符串
sql = ('SELECT count() FROM table '
'WHERE id = "10" '
'GROUP BY sex')
print sql
SELECT count() FROM table WHERE id = "10" GROUP BY sex
———————————————— 版权声明:本文为CSDN博主「yolosliu」的原创文章,遵循CC 4.0 by-sa版权协议,转载请附上原文出处连接及本声明。原文连接:https://blog.csdn.net/github_36601823/article/details/77815013