Python – Convert Strings to Character Matrix

Sometimes, while dealing with String lists, we can have a problem in which we need to convert the Strings in list to separate character list. Overall converting into Matrix. This can have multiple applications in data science domain in which we deal with lots of data. Lets discuss certain ways in which this task can be performed.

Method #1 : Using List comprehension
This is one way in which this task can be performed. In this, we convert the string to list of characters using list() and convert the result to desired matrix.

 `# Python3 code to demonstrate  ` `# Convert Strings to Character Matrix ` `# using List comprehension ` ` `  `# Initializing list ` `test_list ``=` `[``'gfg'``, ``'is'``, ``'best'``] ` ` `  `# printing original list ` `print``(``"The original list is : "` `+` `str``(test_list)) ` ` `  `# Convert Strings to Character Matrix ` `# using List comprehension ` `res ``=` `[``list``(sub) ``for` `sub ``in` `test_list] ` `             `  `# printing result  ` `print` `(``"List String after conversion to Matrix : "` `+` `str``(res)) `

Output :

The original list is : [‘gfg’, ‘is’, ‘best’]
List String after conversion to Matrix : [[‘g’, ‘f’, ‘g’], [‘i’, ‘s’], [‘b’, ‘e’, ‘s’, ‘t’]]

Method #2 : Using `loop + list()`
This is brute force way to perform this task. In this, we run loop and and convert each string to character list using list().

 `# Python3 code to demonstrate  ` `# Convert Strings to Character Matrix ` `# using loop + list() ` ` `  `# Initializing list ` `test_list ``=` `[``'gfg'``, ``'is'``, ``'best'``] ` ` `  `# printing original list ` `print``(``"The original list is : "` `+` `str``(test_list)) ` ` `  `# Convert Strings to Character Matrix ` `# using loop + list() ` `res ``=` `[] ` `for` `sub ``in` `test_list: ` `    ``res.append(``list``(sub)) ` ` `  `# printing result  ` `print` `(``"List String after conversion to Matrix : "` `+` `str``(res)) `

Output :

The original list is : [‘gfg’, ‘is’, ‘best’]
List String after conversion to Matrix : [[‘g’, ‘f’, ‘g’], [‘i’, ‘s’], [‘b’, ‘e’, ‘s’, ‘t’]]

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.