Skip to content
Related Articles

Related Articles

Python – Replace delimiter

View Discussion
Improve Article
Save Article
  • Last Updated : 10 Jul, 2020
View Discussion
Improve Article
Save Article

Given List of Strings and replacing delimiter, replace current delimiter in each string.

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.

Method #1 : Using replace() + loop
The combination of above functions provide a brute force method to solve this problem. In this, a loop is used to iterate through each string and perform replacement using 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))

Output :

The original list is : ['a, t', 'g, f, g', 'w, e', 'd, o']
Replaced List : ['a#t', 'g#f#g', 'w#e', 'd#o']

 

Method #2 : Using list comprehension + replace()
The combination of above functions can provide one liner to this problem. This is similar to above method, just encapsulated in list comprehension.




# 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))

Output :

The original list is : ['a, t', 'g, f, g', 'w, e', 'd, o']
Replaced List : ['a#t', 'g#f#g', 'w#e', 'd#o']

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!