Python Program to Convert Matrix to String

PythonServer Side ProgrammingProgramming

When it is required to convert a matrix into a string, a simple list comprehension along with the ‘join’ method can be used.

Example

Below is a demonstration of the same

my_list = [[1, 23, "python"], [1, "is", 24], ["fun", 97, 5]]

print("The list is :")
print(my_list)

in_delete, out_delete = ",", " "

my_result = out_delete.join([in_delete.join([str(element) for element in sub]) for sub in my_list])

print("The output string is :")
print(my_result)

Output

The list is :
[[1, 23, 'python'], [1, 'is', 24], ['fun', 97, 5]]
The output string is :
1,23,python 1,is,24 fun,97,5

Explanation

  • A list of list is defined and is displayed on the console.

  • Two variables with symbols are defined.

  • A list comprehension is used to iterate through the elements in the list.

  • The elements are joined based on a specific condition.

  • This is assigned to a variable.

  • This variable is displayed as output on the console.

raja
Published on 15-Sep-2021 11:45:51

Advertisements