📜  Python|多个索引替换字符串

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

Python|多个索引替换字符串

有时,在使用Python Stings 时,我们可能会遇到一个问题,即我们需要根据 String 的多个索引执行字符替换。这种问题可以在许多领域都有应用。让我们讨论可以执行此任务的某些方式。

方法 #1:使用loop + join()
这是可以执行此任务的蛮力方式。在这种情况下,我们对每个字符进行迭代,如果是一个则用替换字符替换。

# Python3 code to demonstrate working of 
# Multiple indices Replace in String
# Using loop + join()
  
# initializing string
test_str = 'geeksforgeeks is best'
  
# printing original string
print("The original string is : " + test_str)
  
# initializing list 
test_list = [2, 4, 7, 10]
  
# initializing repl char
repl_char = '*'
  
# Multiple indices Replace in String
# Using loop + join()
temp = list(test_str)
for idx in test_list:
    temp[idx] = repl_char
res = ''.join(temp)
  
# printing result 
print("The String after performing replace : " + str(res)) 
输出 :
The original string is : geeksforgeeks is best
The String after performing replace : ge*k*fo*ge*ks is best

方法 #2:使用列表理解 + join()
上述功能的组合也可用于执行此任务。在此,我们执行与上述类似的任务,只是使用列表理解以一种线性格式。

# Python3 code to demonstrate working of 
# Multiple indices Replace in String
# Using list comprehension + join()
  
# initializing string
test_str = 'geeksforgeeks is best'
  
# printing original string
print("The original string is : " + test_str)
  
# initializing list 
test_list = [2, 4, 7, 10]
  
# initializing repl char
repl_char = '*'
  
# Multiple indices Replace in String
# Using list comprehension + join()
temp = list(test_str)
res = [repl_char if idx in test_list else ele for idx, ele in enumerate(temp)]
res = ''.join(res)
  
# printing result 
print("The String after performing replace : " + str(res)) 
输出 :
The original string is : geeksforgeeks is best
The String after performing replace : ge*k*fo*ge*ks is best