python 字符串替换_Python中的字符串替换操作示例

这篇文章主要介绍了Python中的字符串替换操作示例,包括一则使用字符串模板string.Template的例子及一则使用正则表达式的例子,

字符串的替换(interpolation), 可以使用string.Template, 也可以使用标准字符串的拼接.

string.Template标示替换的字符, 使用"$"符号, 或 在字符串内, 使用"${}"; 调用时使用string.substitute(dict)函数.

标准字符串拼接, 使用"%()s"的符号, 调用时, 使用string%dict方法.

两者都可以进行字符的替换.

代码:

# -*- coding: utf-8 -*-

import string

values = {'var' : 'foo'}

tem = string.Template('''''

Variable : $var

Escape : $$

Variable in text : ${var}iable

''')

print 'TEMPLATE:', tem.substitute(values)

str = '''''

Variable : %(var)s

Escape : %%

Variable in text : %(var)siable

'''

print 'INTERPOLATION:', str%values

输出:

TEMPLATE:

Variable : foo

Escape : $

Variable in text : fooiable

INTERPOLATION:

Variable : foo

Escape : %

Variable in text : fooiable

连续替换(replace)的正则表达式(re)

字符串连续替换, 可以连续使用replace, 也可以使用正则表达式.

正则表达式, 通过字典的样式, key为待替换, value为替换成, 进行一次替换即可.

代码

# -*- coding: utf-8 -*-

import re

my_str = "(condition1) and --condition2--"

print my_str.replace("condition1", "").replace("condition2", "text")

rep = {"condition1": "", "condition2": "text"}

rep = dict((re.escape(k), v) for k, v in rep.iteritems())

pattern = re.compile("|".join(rep.keys()))

my_str = pattern.sub(lambda m: rep[re.escape(m.group(0))], my_str)

print my_str

输出:

() and --text--

() and --text--

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值