Python – 用多个值替换 K
有时,在使用Python字符串时,我们可能会遇到一个问题,即我们需要根据出现情况用特定的值列表替换单个字符/work。这类问题可以在学校和日常编程中应用。让我们讨论可以执行此任务的某些方式。
Input : test_str = ‘* is * . It is recommended for *’, repl_char = ‘*’,
repl_list = [‘Gfg’, ‘Best’, ‘CS’]
Output : Gfg is Best . It is recommended for CS
Input : test_str = ‘* is *’, repl_char = ‘*’,
repl_list = [‘Gfg’, ‘Best’]
Output : Gfg is Best
方法#1:使用循环+ replace()
上述功能的组合可以用来解决这个问题。在此,我们使用 replace() 执行替换任务,并在每次替换后增加索引计数器。
Python3
# Python3 code to demonstrate working of
# Replace K with Multiple values
# Using loop + replace()
# initializing strings
test_str = '_ is _ . It is recommended for _'
# printing original string
print("The original string is : " + str(test_str))
# initializing repl_char
repl_char = '_'
# initializing repl_list
repl_list = ['Gfg', 'Best', 'CS']
# Replace K with Multiple values
# Using loop + replace()
for ele in repl_list:
test_str = test_str.replace(repl_char, ele, 1)
# printing result
print("String after replacement : " + str(test_str))
Python3
# Python3 code to demonstrate working of
# Replace K with Multiple values
# Using split() + join() + zip()
# initializing strings
test_str = '_ is _ . It is recommended for _'
# printing original string
print("The original string is : " + str(test_str))
# initializing repl_char
repl_char = '_'
# initializing repl_list
repl_list = ['Gfg', 'Best', 'CS']
# Replace K with Multiple values
# Using split() + join() + zip()
test_list = test_str.split(repl_char)
temp = zip(test_list, repl_list)
res = ''.join([ele for sub in temp for ele in sub])
# printing result
print("String after replacement : " + str(res))
输出 :
The original string is : _ is _ . It is recommended for _
String after replacement : Gfg is Best . It is recommended for CS
方法 #2:使用split() + join() + zip()
上述功能的组合提供了另一种解决此问题的方法。在此,我们首先使用 split() 拆分单词,使用 zip() 压缩两个需要的列表,然后通过适当的替换重新加入。
Python3
# Python3 code to demonstrate working of
# Replace K with Multiple values
# Using split() + join() + zip()
# initializing strings
test_str = '_ is _ . It is recommended for _'
# printing original string
print("The original string is : " + str(test_str))
# initializing repl_char
repl_char = '_'
# initializing repl_list
repl_list = ['Gfg', 'Best', 'CS']
# Replace K with Multiple values
# Using split() + join() + zip()
test_list = test_str.split(repl_char)
temp = zip(test_list, repl_list)
res = ''.join([ele for sub in temp for ele in sub])
# printing result
print("String after replacement : " + str(res))
输出 :
The original string is : _ is _ . It is recommended for _
String after replacement : Gfg is Best . It is recommended for CS