python标准库string_(转)Python 标准库笔记:string模块

String模块包含大量实用常量和类,以及一些过时的遗留功能,并还可用作字符串操作。

原文:http://www.10tiao.com/html/384/201709/2651305041/1.html

1. 常用方法

2.字符串常量

3.字符串模板Template

通过string.Template可以为Python定制字符串的替换标准,下面是具体列子:

>>>fromstringimportTemplate

>>>s= Template('$who like $what')

>>>prints.substitute(who='i',what='python')

ilike python

>>>prints.safe_substitute(who='i')# 缺少key时不会抛错

ilike$what

>>>Template('${who}LikePython').substitute(who='I')# 在字符串内时使用{}

'ILikePython'

Template还有更加高级的用法,可以通过继承string.Template, 重写变量delimiter(定界符)和idpattern(替换格式), 定制不同形式的模板。

importstring

template_text= ''' Delimiter : $de Replaced : %with_underscore Ingored : %notunderscored '''

d= {'de': 'not replaced',

'with_underscore': 'replaced',

'notunderscored': 'not replaced'}

classMyTemplate(string.Template):

# 重写模板 定界符(delimiter)为"%", 替换模式(idpattern)必须包含下划线(_)

delimiter= '%'

idpattern= '[a-z]+_[a-z]+'

printstring.Template(template_text).safe_substitute(d)# 采用原来的Template渲染

printMyTemplate(template_text).safe_substitute(d)# 使用重写后的MyTemplate渲染

输出:

Delimiter: notreplaced

Replaced: %with_underscore

Ingored: %notunderscored

Delimiter: $de

Replaced: replaced

Ingored: %notunderscored

原生的Template只会渲染界定符为$的情况,重写后的MyTemplate会渲染界定符为%且替换格式带有下划线的情况。

4.常用字符串技巧

1.反转字符串

>>> s= '1234567890'

>>> prints[::-1]

0987654321

2.关于字符串链接

尽量使用join()链接字符串,因为’+’号连接n个字符串需要申请n-1次内存,使用join()需要申请1次内存。

3.固定长度分割字符串

>>> importre

>>> s= '1234567890'

>>> re.findall(r'.{1,3}',s)# 已三个长度分割字符串

['123','456','789','0']

4.使用()括号生成字符串

sql= ('SELECT count() FROM table '

'WHERE id = "10" '

'GROUP BY sex')

printsql

SELECTcount()FROMtable WHERE id= "10"GROUP BY sex

5.将print的字符串写到文件

>>> print >> open("somefile.txt", "w+"), "Hello World"  # Hello World将写入文件somefile.txt

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值