Python | Split flatten String List

Sometimes, while working with Python Strings, we can have problem in which we need to perform the split of strings on a particular deliminitor. In this, we might need to flatten this to a single String List. Lets discuss certain ways in which this task can be performed.

Method #1 : Using list comprehension + split() + extend()
The combination of above functions can be used to perform this task. In this, we perform the task of split, using split() and add split elements in list using extend().

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Split flatten String List
# Using list comprehension + split() + extend()
      
# initializing list
test_list = ['gfg-is-best', 'for-all', 'geeks-and', 'CS']
  
# printing original list
print("The original list is : " + str(test_list))
  
# Split flatten String List
# Using list comprehension + split() + extend()
res = []
[res.extend(idx.split("-")) for idx in test_list] 
  
# printing result 
print("The String List after extension : " + str(res)) 

chevron_right


Output :

The original list is : ['gfg-is-best', 'for-all', 'geeks-and', 'CS']
The String List after extension : ['gfg', 'is', 'best', 'for', 'all', 'geeks', 'and', 'CS']

 

Method #2 : Using split() + join()
This is one of the way in which this task can be performed. In this, we perform the task of extension using join() and split().

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Split flatten String List
# Using split() + join()
      
# initializing list
test_list = ['gfg-is-best', 'for-all', 'geeks-and', 'CS']
  
# printing original list
print("The original list is : " + str(test_list))
  
# Split flatten String List
# Using split() + join()
res = '-'.join(test_list).split('-')
  
# printing result 
print("The String List after extension : " + str(res)) 

chevron_right


Output :

The original list is : ['gfg-is-best', 'for-all', 'geeks-and', 'CS']
The String List after extension : ['gfg', 'is', 'best', 'for', 'all', 'geeks', 'and', 'CS']



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.