Python | Delimited String List to String Matrix

Sometimes, while working with Python strings, we can have problem in which we need to convert String list which have strings that are joined by deliminitor to String Matrix by separation by deliminitor. Lets discuss certain ways in which this task can be performed.

Method #1 : Using loop + split()
This is one of way in which this task can be performed. In this, we iterate for each string and perform the split using split().

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Delimited String List to String Matrix
# Using loop + split()
  
# initializing list
test_list = ['gfg:is:best', 'for:all', 'geeks:and:CS']
  
# printing original list
print("The original list is : " + str(test_list))
  
# Delimited String List to String Matrix
# Using loop + split()
res = []
for sub in test_list:
    res.append(sub.split(':'))
  
# printing result 
print("The list after conversion : " + str(res)) 

chevron_right


Output :

The original list is : ['gfg:is:best', 'for:all', 'geeks:and:CS']
The list after conversion : [['gfg', 'is', 'best'], ['for', 'all'], ['geeks', 'and', 'CS']]

 

Method #2 : Using list comprehension + split()
Yet another way to perform this task, is just modification of above method. In this, we use list comprehension as shorthand and one-liner to perform this.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output :

The original list is : ['gfg:is:best', 'for:all', 'geeks:and:CS']
The list after conversion : [['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.