Skip to content
Related Articles

Related Articles

Improve Article

Python – Replace delimiter

  • Last Updated : 10 Jul, 2020

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']

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :