gpt4 book ai didi

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

转载 作者:qq735679552 更新时间:2022-09-29 22:32:09 26 4
gpt4 key购买 nike

CFSDN坚持开源创造价值,我们致力于搭建一个资源共享平台,让每一个IT人在这里找到属于你的精彩世界.

这篇CFSDN的博客文章Python中的字符串替换操作示例由作者收集整理,如果你对这篇文章有兴趣,记得点赞哟.

字符串的替换(interpolation), 可以使用string.Template, 也可以使用标准字符串的拼接. string.Template标示替换的字符, 使用"$"符号, 或 在字符串内, 使用"${}"; 调用时使用string.substitute(dict)函数. 标准字符串拼接, 使用"%()s"的符号, 调用时, 使用string%dict方法. 两者都可以进行字符的替换. 。

代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# -*- 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

输出

?
1
2
3
4
5
6
7
8
9
TEMPLATE: 
Variable : foo
Escape : $
Variable in text : fooiable
 
INTERPOLATION: 
Variable : foo
Escape : %
Variable in text : fooiable

连续替换(replace)的正则表达式(re) 字符串连续替换, 可以连续使用replace, 也可以使用正则表达式. 正则表达式, 通过字典的样式, key为待替换, value为替换成, 进行一次替换即可. 。

代码 。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
# -*- 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

输出

?
1
2
() and --text--
() and --text--

最后此篇关于Python中的字符串替换操作示例的文章就讲到这里了,如果你想了解更多关于Python中的字符串替换操作示例的内容请搜索CFSDN的文章或继续浏览相关文章,希望大家以后支持我的博客! 。

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com