VOOZH about

URL: https://www.geeksforgeeks.org/python/python-convert-character-matrix-to-single-string/

⇱ Convert Character Matrix to single String - Python - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Convert Character Matrix to single String - Python

Last Updated : 12 Jul, 2025

In this article, we will explore various methods to convert character matrix to single string in Python. The simplest way to do is by using a loop.

Using a Loop

We can use a loop (for loop) to iterate through each sublist and concatenate the elements of each sublist and then combine them into a final string.


Output
gfgisbest

Explanation:

  • ''.join(sublist): Concatenates each element of sublist into a single string.
  • res += ''.join(sublist): This adds the resulting string to the final res string this building it up as we loop through the matrix.

Using List Comprehension and join()

We can use list comprehension with join() method. This method allows us to concatenate all the elements in an iterable into a single string.


Output
gfgisbest

Explanation:

  • ''.join(sublist): This concatenates each sublist (row) into a string. For example, ['g', 'f', 'g'] becomes 'gfg'.
  • [''.join(sublist) for sublist in a]: List comprehension is used to apply join() method to each sublist in the matrix.
  • ''.join(): Finally, we use ''.join() to concatenate all the individual strings into a single string.

Using itertools.chain()

For a memory-efficient solution, we can use itertools.chain() to flatten the matrix.


Explanation:

  • chain.from_iterable() flattens the matrix in a memory-efficient way.
  • The result is then passed to join().



Comment