Python – 替换分隔符
给定字符串列表和替换分隔符,替换每个字符串中的当前分隔符。
Input : test_list = [“a, t”, “g, f, g”, “w, e”, “d, o”], repl_delim = ‘ ‘
Output : [“a t”, “g f g”, “w e”, “d o”]
Explanation : comma is replaced by empty spaces at each string.
Input : test_list = [“g#f#g”], repl_delim = ‘, ‘
Output : [“g, f, g”]
Explanation : hash is replaced by comma at each string.
方法 #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']