Skip to content
Related Articles

Related Articles

Python – Convert List to delimiter separated String

View Discussion
Improve Article
Save Article
  • Last Updated : 30 Aug, 2022
View Discussion
Improve Article
Save Article

Given a List of elements, convert it to delimiter separated String.

Input : test_list = [7, “Gfg”, “best”, 9], delim = “*” 

Output : 7*Gfg*best*9* 

Explanation : All elements are concatenated with “*” as joiner. 

Input : test_list = [7, “Gfg”, “best”, 9], delim = “#” 

Output : 7#Gfg#best#9# 

Explanation : All elements are concatenated with “#” as joiner.

Method #1 : Using loop + str()

This is one of the ways in which this task can be performed. In this, we run a loop to add delimiter at end of each element, after converting each element to  string.

Python3




# Python3 code to demonstrate working of
# Convert List to delimiter separated String
# Using loop + str()
 
# initializing list
test_list = [7, "Gfg", 8, "is", "best", 9]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing delim
delim = "*"
 
res = ''
 
# using loop to add string followed by delim
for ele in test_list:
    res = res + str(ele) + delim
 
# printing result
print("The resultant string : " + str(res))

Output

The original list is : [7, 'Gfg', 8, 'is', 'best', 9]
The resultant string : 7*Gfg*8*is*best*9*

Method #2 : Using join() + str()

This is yet another way in which this task can be performed. In this we perform the task of joining each element by delim using join() and conversion to string is done using str().

Python3




# Python3 code to demonstrate working of
# Convert List to delimiter separated String
# Using join() + str()
 
# initializing list
test_list = [7, "Gfg", 8, "is", "best", 9]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing delim
delim = "*"
 
# using map to convert each element to string
temp = list(map(str, test_list))
 
# join() used to join with delimiter
res = delim.join(temp)
 
# printing result
print("The resultant string : " + str(res))

Output

The original list is : [7, 'Gfg', 8, 'is', 'best', 9]
The resultant string : 7*Gfg*8*is*best*9

Time Complexity: O(n)

Auxiliary Space: O(n)


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!