Python | Convert Character Matrix to single String

Sometimes, while working with Python strings, we can have an option in which we need to perform the task of converting character matrix to a single string. This can have applications in domains in which we need to work with data. Lets discuss certain ways in which we can perform this task.

Method #1 : Using join() + list comprehension
The combination of above functionalities can be used to perform this task. In this, we just iterate for all lists and join them using join().

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Convert Character Matrix to single String
# Using join() + list comprehension
  
# initializing list
test_list = [['g', 'f', 'g'], ['i', 's'], ['b', 'e', 's', 't']]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Convert Character Matrix to single String
# Using join() + list comprehension
res = ''.join(ele for sub in test_list for ele in sub)
  
# printing result 
print("The String after join : " + res) 

chevron_right


Output :

The original list is : [['g', 'f', 'g'], ['i', 's'], ['b', 'e', 's', 't']]
The String after join : gfgisbest

 

Method #2 : Using join() + chain()
The combination of above functionalities can be used to perform this task. In this, we perform the task performed by list comprehension by chain().

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of 
# Convert Character Matrix to single String
# Using join() + chain()
from itertools import chain
  
# initializing list
test_list = [['g', 'f', 'g'], ['i', 's'], ['b', 'e', 's', 't']]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Convert Character Matrix to single String
# Using join() + chain()
res = "".join(chain(*test_list))
  
# printing result 
print("The String after join : " + res) 

chevron_right


Output :

The original list is : [['g', 'f', 'g'], ['i', 's'], ['b', 'e', 's', 't']]
The String after join : gfgisbest



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.