📜  Python – 替换分隔符

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

Python – 替换分隔符

给定字符串列表和替换分隔符,替换每个字符串中的当前分隔符。

方法 #1:使用replace() + 循环
上述功能的组合提供了一种蛮力方法来解决这个问题。在此,循环用于遍历每个字符串并使用 replace() 执行替换。

# Python3 code to demonstrate working of 
# Replace delimiter
# Using loop + replace()
  
# initializing list
test_list = ["a, t", "g, f, g", "w, e", "d, o"] 
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing replace delimiter
repl_delim = '#'
  
# Replace delimiter
res = []
for ele in test_list:
       
    # adding each string after replacement using replace()
    res.append(ele.replace(", ", repl_delim))
  
# printing result 
print("Replaced List : " + str(res))
输出 :
The original list is : ['a, t', 'g, f, g', 'w, e', 'd, o']
Replaced List : ['a#t', 'g#f#g', 'w#e', 'd#o']

方法 #2:使用列表理解 + replace()
上述功能的组合可以为这个问题提供一条线。这类似于上面的方法,只是封装在列表推导中。

# Python3 code to demonstrate working of 
# Replace delimiter
# Using list comprehension + replace()
  
# initializing list
test_list = ["a, t", "g, f, g", "w, e", "d, o"] 
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing replace delimiter
repl_delim = '#'
  
# Replace delimiter
# iterating inside comprehension, performing replace using replace()
res = [sub.replace(', ', repl_delim) for sub in test_list]
  
# printing result 
print("Replaced List : " + str(res))
输出 :
The original list is : ['a, t', 'g, f, g', 'w, e', 'd, o']
Replaced List : ['a#t', 'g#f#g', 'w#e', 'd#o']