Python 标准库笔记:string模块
来源:互联网 发布:js中input设置默认值 编辑:程序博客网 时间:2024/06/07 10:03
1. 常用方法
2.字符串常量
3.字符串模板Template
通过string.Template可以为Python定制字符串的替换标准,下面是具体列子:
>>>from string import Template
>>>s = Template('$who like $what')
>>>print s.substitute(who='i', what='python')
i like python
>>>print s.safe_substitute(who='i') # 缺少key时不会抛错
i like $what
>>>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
5.将print的字符串写到文件
>>> print >> open("somefile.txt", "w+"), "Hello World" # Hello World将写入文件somefile.txt
- Python 标准库笔记:string模块
- python学习笔记4-python模块和标准库
- 《python标准库》学习笔记1(__builtin__模块)
- Python标准库-traceback模块
- Python标准库-random模块
- Python 标准库 cmd模块
- python标准库random模块
- Python标准库-traceback模块
- Python标准库os模块
- Python标准库:itertools模块
- Python标准库笔记
- 标准库类型string笔记
- [python]python标准库(模块)简介
- Python标准库——os模块
- python标准库logging模块代码分析
- Python 3.x标准模块库目录
- Python 3.x标准模块库目录
- Python标准库之os模块
- C++ 中vector的使用方法
- Tyvj1054
- python里使用asyncore模块
- Nginx自动缓存文件的问题
- 001-支持并发的两次判空懒汉单例
- Python 标准库笔记:string模块
- centos 7 网络配置
- 怎样设置 Docker 监控
- TortoiseSVN教程
- 排列问题
- SQLServer --自定义带输入参数的存储过程
- JUC源码解析(6)-locks-AbstractQueuedSynchronizer
- 二进制和十进制之间的转换
- World is Exploding HDU