Python | Convert String list to Joined Single element

Sometimes, while working with Python, we can have a problem in which we need to perform the task of joining each element of String list to a single element in List by combining using delim. This kind of application can come in web development domain. Lets discuss certain ways in which this task can be performed.

Method #1 : Using loop
This is one of way to perform this task. In this, we iterate for the String list for strings using loop and perform the join operation according to the delim.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Convert String list to Joined Single element
# Using loop
  
# initializing list
test_list = ['gfg', 'is', 'best']
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing delim 
delim = "-"
  
# Convert String list to Joined Single element
# Using loop
res = ''  
for idx in range(len(test_list)-1):
    res = res + test_list[idx] + delim
if len(test_list) > 0:
        res = res + test_list[-1]
res = [res]
  
# printing result 
print("String after performing join : " + str(res)) 

chevron_right


Output :



The original list is : ['gfg', 'is', 'best']
String after performing join : ['gfg-is-best']

 

Method #2 : Using join() + list comprehension
This task can also be performed using the combination of above functions. In this, we perform the task of combining using join(). The logic is compiled using list comprehension.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Convert String list to Joined Single element
# Using join() + list comprehension
  
# initializing list
test_list = ['gfg', 'is', 'best']
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing delim 
delim = "-"
  
# Convert String list to Joined Single element
# Using join() + list comprehension
res =  [delim.join(test_list)]
  
# printing result 
print("String after performing join : " + str(res)) 

chevron_right


Output :

The original list is : ['gfg', 'is', 'best']
String after performing join : ['gfg-is-best']



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.