📜  Python – 一次替换字符串中的不同字符

📅  最后修改于: 2022-05-13 01:54:20.145000             🧑  作者: Mango

Python – 一次替换字符串中的不同字符

给定要替换为相应值的字符映射,在一个行中一次执行所有替换。

方法 #1:使用 join() + 生成器表达式

在此,我们执行获取字典中存在的字符并通过字典访问将它们映射到它们的值的任务,所有其他字符都保持不变,结果使用 join() 转换回字典。

Python3
# Python3 code to demonstrate working of
# Replace Different characters in String at Once
# using join() + generator expression
 
# initializing string
test_str = 'geeksforgeeks is best'
 
# printing original String
print("The original string is : " + str(test_str))
 
# initializing mapping dictionary
map_dict = {'e':'1', 'b':'6', 'i':'4'}
 
# generator expression to construct vals
# join to get string
res = ''.join(idx if idx not in map_dict else map_dict[idx] for idx in test_str)
 
# printing result
print("The converted string : " + str(res))


Python3
# Python3 code to demonstrate working of
# Replace Different characters in String at Once
# using regex + lambda
import re
 
# initializing string
test_str = 'geeksforgeeks is best'
 
# printing original String
print("The original string is : " + str(test_str))
 
# initializing mapping dictionary
map_dict = {'e':'1', 'b':'6', 'i':'4'}
 
# using lambda and regex functions to achieve task
res = re.compile("|".join(map_dict.keys())).sub(lambda ele: map_dict[re.escape(ele.group(0))], test_str)
 
# printing result
print("The converted string : " + str(res))


输出
The original string is : geeksforgeeks is best
The converted string : g11ksforg11ks 4s 61st

方法 #2:使用正则表达式 + lambda

这是处理问题的复杂方法。在此,我们使用 lambda 函数构造适当的正则表达式并执行所需的替换任务。

Python3

# Python3 code to demonstrate working of
# Replace Different characters in String at Once
# using regex + lambda
import re
 
# initializing string
test_str = 'geeksforgeeks is best'
 
# printing original String
print("The original string is : " + str(test_str))
 
# initializing mapping dictionary
map_dict = {'e':'1', 'b':'6', 'i':'4'}
 
# using lambda and regex functions to achieve task
res = re.compile("|".join(map_dict.keys())).sub(lambda ele: map_dict[re.escape(ele.group(0))], test_str)
 
# printing result
print("The converted string : " + str(res))
输出
The original string is : geeksforgeeks is best
The converted string : g11ksforg11ks 4s 61st