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

Example of string replacement operation in Python

WBOY
Release: 2016-07-06 13:29:43
Original
1223 people have browsed it

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 

Copy after login

Output:

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

Copy after login

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

Copy after login

Output:

() and --text--
() and --text--
Copy after login

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template