Open In App

Python – Convert Integer Matrix to String Matrix

Last Updated : 23 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a matrix with integer values, convert each element to String.

Input : test_list = [[4, 5, 7], [10, 8, 3], [19, 4, 6]]
Output : [['4', '5', '7'], ['10', '8', '3'], ['19', '4', '6']] 
Explanation : All elements of Matrix converted to Strings. 
Input : test_list = [[4, 5, 7], [10, 8, 3]] 
Output : [['4', '5', '7'], ['10', '8', '3']] 
Explanation : All elements of Matrix converted to Strings.

Method #1 : Using str() + list comprehension

The combination of the above methods can be used to solve this problem. In this, we perform the conversion using str(), and list comprehension is used to iterate for all the elements.

Python3




# Python3 code to demonstrate working of
# Convert Integer Matrix to String Matrix
# Using str() + list comprehension
 
# initializing list
test_list = [[4, 5, 7], [10, 8, 3], [19, 4, 6], [9, 3, 6]]
 
# printing original list
print("The original list : " + str(test_list))
 
# using str() to convert each element to string
res = [[str(ele) for ele in sub] for sub in test_list]
 
# printing result
print("The data type converted Matrix : " + str(res))


Output

The original list : [[4, 5, 7], [10, 8, 3], [19, 4, 6], [9, 3, 6]]
The data type converted Matrix : [['4', '5', '7'], ['10', '8', '3'], ['19', '4', '6'], ['9', '3', '6']]

Method #2 : Using str() + map()

The combination of above functions can also be used to solve this problem. In this, we use map() to extend the string conversion to all row elements.

Python3




# Python3 code to demonstrate working of
# Convert Integer Matrix to String Matrix
# Using str() + map()
 
# initializing list
test_list = [[4, 5, 7], [10, 8, 3], [19, 4, 6], [9, 3, 6]]
 
# printing original list
print("The original list : " + str(test_list))
 
# using map() to extend all elements as string 
res = [list(map(str, sub)) for sub in test_list]
 
# printing result
print("The data type converted Matrix : " + str(res))


Output

The original list : [[4, 5, 7], [10, 8, 3], [19, 4, 6], [9, 3, 6]]
The data type converted Matrix : [['4', '5', '7'], ['10', '8', '3'], ['19', '4', '6'], ['9', '3', '6']]

The Time and Space Complexity for all the methods are the same:

Time Complexity: O(n2)
Auxiliary Space: O(n)

Method #3: Using numpy.char.mod() function.

Algorithm:

  1. Convert the input list into a numpy array using numpy.array() function.
  2. Use numpy.char.mod() function to convert the elements of the array to strings. %s format specifier is used to indicate string conversion.
  3. Convert the resulting numpy array back to a list using tolist() method.

Python3




import numpy as np
# initializing list
test_list = [[4, 5, 7], [10, 8, 3], [19, 4, 6], [9, 3, 6]]
 
# printing original list
print("The original list : " + str(test_list))
 
matrix = np.array(test_list)
res = np.char.mod('%s', matrix).tolist()
 
# printing result
print("The data type converted Matrix : " + str(res))


Output

The original list : [[4, 5, 7], [10, 8, 3], [19, 4, 6], [9, 3, 6]]
The data type converted Matrix : [[‘4’, ‘5’, ‘7’], [’10’, ‘8’, ‘3’], [’19’, ‘4’, ‘6’], [‘9’, ‘3’, ‘6’]]

Time Complexity:

The time complexity of this algorithm is O(m * n), where m is the number of rows and n is the number of columns in the input matrix. This is because we are iterating over each element of the matrix once to convert it to a string.

Space Complexity:

The space complexity of this algorithm is also O(m * n), as we are creating a new numpy array of the same size as the input matrix and then converting it to a list. However, the memory usage of numpy arrays is typically more efficient than Python lists, so this method may be more memory-efficient than other methods that use Python lists.

Iterative String Conversion

We can iterate through each element of the matrix and convert it to a string using the str() function. We will store the converted elements in a new matrix of the same size as the original matrix.

Steps:

  1. Initialize an empty matrix with the same size as the input matrix.
  2. Iterate through each element in the input matrix using nested loops.
  3. Convert each element to string using the str() function and store it in the corresponding location in the new matrix.
  4. Return the new matrix. 
     

Python3




def convert_matrix_to_string(test_list):
    rows = len(test_list)
    cols = len(test_list[0])
    string_matrix = [[''] * cols for _ in range(rows)]
    for i in range(rows):
        for j in range(cols):
            string_matrix[i][j] = str(test_list[i][j])
    return string_matrix
 
test_list = [[4, 5, 7], [10, 8, 3], [19, 4, 6]]
string_matrix = convert_matrix_to_string(test_list)
print(string_matrix)


Output

[['4', '5', '7'], ['10', '8', '3'], ['19', '4', '6']]

The time complexity of this approach is O(m*n), where m and n are the dimensions of the input matrix. 
The auxiliary space used by this approach is also O(m*n).

Method 5: Using a nested loop.

Step-by-step approach:

  • Initialize an empty list to store the converted string matrix.
  • Use a nested loop to iterate over the elements of the integer matrix.
  • Convert each element to a string using the str() function and append it to a temporary list.
  • After converting all the elements in a row, append the temporary list to the result list.
  • Repeat the above steps for all the rows in the integer matrix.
  • Print the original list and the converted string matrix.

Python3




# initializing list
test_list = [[4, 5, 7], [10, 8, 3], [19, 4, 6], [9, 3, 6]]
 
# printing original list
print("The original list : " + str(test_list))
 
# converting integer matrix to string matrix
str_matrix = []
for row in test_list:
    str_row = []
    for element in row:
        str_row.append(str(element))
    str_matrix.append(str_row)
 
# printing result
print("The data type converted Matrix : " + str(str_matrix))


Output

The original list : [[4, 5, 7], [10, 8, 3], [19, 4, 6], [9, 3, 6]]
The data type converted Matrix : [['4', '5', '7'], ['10', '8', '3'], ['19', '4', '6'], ['9', '3', '6']]

Time complexity: O(mn), where m is the number of rows and n is the number of columns in the matrix.
Auxiliary space: O(mn), to store the converted string matrix.



Previous Article
Next Article

Similar Reads

Python | Convert list of string into sorted list of integer
Given a list of string, write a Python program to convert it into sorted list of integer. Examples: Input: ['21', '1', '131', '12', '15'] Output: [1, 12, 15, 21, 131] Input: ['11', '1', '58', '15', '0'] Output: [0, 1, 11, 15, 58] Let's discuss different methods we can achieve this task. Method #1: Using map and sorted() C/C++ Code # Python code to
4 min read
Python - Convert Alternate String Character to Integer
Interconversion between data types is facilitated by python libraries quite easily. But the problem of converting the alternate list of string to integers is quite common in development domain. Let’s discuss few ways to solve this particular problem. Method #1 : Naive Method This is most generic method that strikes any programmer while performing t
5 min read
Python - Convert Tuple String to Integer Tuple
Interconversion of data is a popular problem developer generally deal with. One can face a problem to convert tuple string to integer tuple. Let's discuss certain ways in which this task can be performed. Method #1 : Using tuple() + int() + replace() + split() The combination of above methods can be used to perform this task. In this, we perform th
7 min read
Convert integer to string in Python
In Python an integer can be converted into a string using the built-in str() function. The str() function takes in any python data type and converts it into a string. But use of the str() is not the only way to do so. This type of conversion can also be done using the "%s" keyword, the .format function or using f-string function. Below is the list
3 min read
How to convert string to integer in Python?
In Python, a string can be converted into an integer using the following methods : Method 1: Using built-in int() function: If your string contains a decimal integer and you wish to convert it into an int, in that case, pass your string to int() function and it will convert your string into an equivalent decimal integer. Syntax : int(string, base)
3 min read
Convert Hex String To Integer in Python
Hexadecimal representation is commonly used in computer science and programming, especially when dealing with low-level operations or data encoding. In Python, converting a hex string to an integer is a frequent operation, and developers have multiple approaches at their disposal to achieve this task. In this article, we will explore various method
2 min read
Python Program to convert List of Integer to List of String
Given a List of Integers. The task is to convert them to a List of Strings. Examples: Input: [1, 12, 15, 21, 131]Output: ['1', '12', '15', '21', '131']Input: [0, 1, 11, 15, 58]Output: ['0', '1', '11', '15', '58']Method 1: Using map() [GFGTABS] Python3 # Python code to convert list of # string into sorted list of integer # List initialization list_i
5 min read
How to Convert String to Integer in Pandas DataFrame?
Let's see methods to convert string to an integer in Pandas DataFrame: Method 1: Use of Series.astype() method. Syntax: Series.astype(dtype, copy=True, errors=’raise’) Parameters: This method will take following parameters: dtype: Data type to convert the series into. (for example str, float, int).copy: Makes a copy of dataframe/series.errors: Erro
3 min read
Python Program to Convert String Matrix Representation to Matrix
Given a String with matrix representation, the task here is to write a python program that converts it to a matrix. Input : test_str = "[gfg,is],[best,for],[all,geeks]"Output : [['gfg', 'is'], ['best', 'for'], ['all', 'geeks']]Explanation : Required String Matrix is converted to Matrix with list as data type. Input : test_str = "[gfg,is],[for],[all
4 min read
Python Program to Convert a list of multiple integers into a single integer
Given a list of integers, write a Python program to convert the given list into a single integer. Examples: Input : [1, 2, 3] Output : 123 Input : [55, 32, 890] Output : 5532890 There are multiple approaches possible to convert the given list into a single integer. Let's see each one by one. Approach #1 : Naive Method Simply iterate each element in
4 min read
three90RightbarBannerImg