Home >Backend Development >Python Tutorial >Example of string replacement operation in Python

Example of string replacement operation in Python

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-07-06 13:29:431245browse

For string replacement (interpolation), you can use string.Template, or you can use standard string concatenation.
string.Template indicates the replaced characters, using the "$" symbol, or within the string, using "${}"; use the string.substitute(dict) function when calling.
For standard string concatenation, use the "%()s" symbol. When calling, use the string%dict method.
Both can replace characters.

Code:

# -*- 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 

Output:

TEMPLATE:  
Variable : foo 
Escape : $ 
Variable in text : fooiable 
 
INTERPOLATION:  
Variable : foo 
Escape : % 
Variable in text : fooiable 

Regular expression (re) for continuous replacement (replace)
Continuous string replacement, you can use replace continuously, or you can use regular expressions.
Regular expression, through the dictionary style, the key is to be replaced, the value is to be replaced, and it can be replaced once.

Code

# -*- 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

Output:

() and --text--
() and --text--

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn