Python中的字符串替换操作示例

yipeiwu_com5年前Python基础

字符串的替换(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--

相关文章

python虚拟环境virtualenv的使用教程

virtualenv 是一个创建隔绝的Python环境的工具。virtualenv创建一个包含所有必要的可执行文件的文件夹,用来使用Python工程所需的包。 安装 pip inst...

利用python打印出菱形、三角形以及矩形的方法实例

前言 本文主要给大家介绍了关于利用python打印出菱形、三角形以及矩形的相关内容,分享出来供大家参考学习,话不多说,来一起看看详细的介绍: 实例代码 #coding:utf-8...

centos 安装Python3 及对应的pip教程详解

安装Python3 安装Python依赖: yum install openssl-devel bzip2-devel expat-devel gdbm-devel readline-d...

pytorch中的卷积和池化计算方式详解

pytorch中的卷积和池化计算方式详解

TensorFlow里面的padding只有两个选项也就是valid和same pytorch里面的padding么有这两个选项,它是数字0,1,2,3等等,默认是0 所以输出的h和w的...

Dlib+OpenCV深度学习人脸识别的方法示例

Dlib+OpenCV深度学习人脸识别的方法示例

前言 人脸识别在LWF(Labeled Faces in the Wild)数据集上人脸识别率现在已经99.7%以上,这个识别率确实非常高了,但是真实的环境中的准确率有多少呢?我没有这方...