Open In App

Python Program to Convert String Matrix Representation to Matrix

Last Updated : 02 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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,geeks]”
Output : [[‘gfg’, ‘is’], [‘for’], [‘all’, ‘geeks’]]
Explanation : Required String Matrix is converted to Matrix with list as data type.

Method 1 : Using split() and regex expression

In this, a plain list is constructed using appropriate regex expression and split() performs the task of getting inner dimension for 2D Matrix.

Example:

Python3




import re
 
# initializing string
test_str = "[gfg,is],[best,for],[all,geeks]"
 
# printing original string
print("The original string is : " + str(test_str))
 
flat_1 = re.findall(r"\[(.+?)\]", test_str)
res = [sub.split(",") for sub in flat_1]
 
# printing result
print("The type of result : " + str(type(res)))
print("Converted Matrix : " + str(res))


Output

The original string is : [gfg,is],[best,for],[all,geeks]
The type of result : <class 'list'>
Converted Matrix : [['gfg', 'is'], ['best', 'for'], ['all', 'geeks']]

Method 2 : Using json.loads()

In this, the task of conversion to the matrix is done using the unbuilt method of loads() of JSON library.

Example:

Python3




# Python3 code to demonstrate working of
# Convert String Matrix Representation to Matrix
# Using json.loads()
import json
 
# initializing string
test_str = '[["gfg", "is"], ["best", "for"], ["all", "geeks"]]'
 
# printing original string
print("The original string is : " + str(test_str))
 
# inbuild function performing task of conversion
# notice input
res = json.loads(test_str)
 
# printing result
print("The type of result : " + str(type(res)))
print("Converted Matrix : " + str(res))


Output

The original string is : [["gfg", "is"], ["best", "for"], ["all", "geeks"]]
The type of result : <class 'list'>
Converted Matrix : [['gfg', 'is'], ['best', 'for'], ['all', 'geeks']]

Method 3: Using string manipulation and list comprehension

We can use string manipulation to extract the individual elements of the matrix, and then use a list comprehension to create a new matrix with those elements.

Algorithm:

1. Remove the square brackets from the string using string manipulation.
2. Split the string into rows using the comma and newline characters as delimiters.
3. Split each row into its individual elements using the comma as a delimiter.
4. Create a new matrix with the elements using a list comprehension.

Python3




test_str = "[gfg,is],[best,for],[all,geeks]"
 
# Remove the square brackets and split into rows
rows = test_str[1:-1].split("],[")
matrix = []
 
# Split each row into its individual elements and create the new matrix
for row in rows:
    elements = row.split(",")
    matrix.append(elements)
 
print(matrix)


Output

[['gfg', 'is'], ['best', 'for'], ['all', 'geeks']]

Time complexity: O(n)
Space complexity: O(n)

Method 4: Use a combination of re.findall() and re.split() functions from the re module.

Step-by-step approach:

  • Import the re module.
  • Define a test string test_str containing comma-separated values inside brackets.
  • Use the re.findall() function with the pattern r’\[([^]]+)\]’ to find all comma-separated values inside brackets in the test_str string. This pattern matches an opening bracket (\[), followed by one or more characters that are not a closing bracket ([^]]+), followed by a closing bracket (\]).
  • Store the resulting list of strings in the values variable.
  • Use a list comprehension to split each value string into a list of strings using the re.split() function with a comma as the separator. The resulting list of lists is stored in the matrix 
  • variable.Print the matrix variable to display the resulting matrix.

Python3




import re
 
test_str = "[gfg,is],[best,for],[all,geeks]"
# Find all comma-separated values inside brackets
values = re.findall(r'\[([^]]+)\]', test_str)
# Split each value into a list of strings
matrix = [re.split(',', value) for value in values]
print(matrix)


Output

[['gfg', 'is'], ['best', 'for'], ['all', 'geeks']]

Time complexity: O(n), where n is the length of the input string. 
Auxiliary space: O(n), where n is the length of the input string. 



Previous Article
Next Article

Similar Reads

Python | Convert a string representation of list into list
Many times, we come across the dumped data that is found in the string format and we require it to be represented in the actual list format in which it was actually found. This kind of problem of converting a list represented in string format back to a list in Python to perform tasks is quite common in web development. Convert a string of a list in
6 min read
Python - Convert Integer Matrix to String Matrix
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 : A
6 min read
Python program to Convert a Matrix to Sparse Matrix
Given a matrix with most of its elements as 0, we need to convert this matrix into a sparse matrix in Python. Example: Input: Matrix: 1 0 0 0 0 2 0 0 0 0 3 0 0 0 0 4 5 0 0 0 Output: Sparse Matrix: 0 0 1 1 1 2 2 2 3 3 3 4 4 0 5 Explanation: Here the Matrix is represented using a 2D list and the Sparse Matrix is represented in the form Row Column Val
3 min read
Python Program for Zeckendorf\'s Theorem (Non-Neighbouring Fibonacci Representation)
Given a number, find a representation of number as sum of non-consecutive Fibonacci numbers. Examples: Input: n = 10 Output: 8 2 8 and 2 are two non-consecutive Fibonacci Numbers and sum of them is 10. Input: n = 30 Output: 21 8 1 21, 8 and 1 are non-consecutive Fibonacci Numbers and sum of them is 30. The idea is to use Greedy Algorithm. 1) Let n
2 min read
Python Program to Convert Matrix to String
Given a matrix, our task is to write a Python program to convert to the matrix, with different delimiters for element and row separation. Examples: Input : test_list = test_list = [[1, 3, "gfg"], [2, "is", 4], ["best", 9, 5]], in_del, out_del = ",", " " Output : 1,3,gfg 2,is,4 best,9,5 Explanation : Element in list separated by ",", and lists separ
5 min read
Python - Convert Matrix to Custom Tuple Matrix
Sometimes, while working with Python Matrix, we can have a problem in which we need to perform conversion of a Python Matrix to matrix of tuples which a value attached row-wise custom from external list. This kind of problem can have applications in data domains as Matrix is integral DS that is used. Let's discuss certain ways in which this task ca
6 min read
Convert covariance matrix to correlation matrix using Python
In this article, we will be discussing the relationship between Covariance and Correlation and program our own function for calculating covariance and correlation using python. Covariance: It tells us how two quantities are related to one another say we want to calculate the covariance between x and y the then the outcome can be one of these. [Tex]
5 min read
Check if Binary representation is Palindrome in Python
Given an integer ‘n’, write a Python function that returns true if binary representation of x is palindrome else return false. Examples: Input : n = 9 Output : True Binary representation of n=9 is 1001 which is palindrome as well. Input : n = 10 Output : False Binary representation of n=10 is 1010 which is not palindrome. We have existing solution
4 min read
Python Map | Length of the Longest Consecutive 1's in Binary Representation of a given integer
Given a number n, find length of the longest consecutive 1s in its binary representation. Examples: Input : n = 14 Output : 3 The binary representation of 14 is 1110. Input : n = 222 Output : 4 The binary representation of 222 is 11011110. We have existing solution for this problem please refer Length of the Longest Consecutive 1s in Binary Represe
3 min read
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 a character matrix to a single string. This can have applications in domains in which we need to work with data. Let us discuss certain ways in which we can perform this task. Method #1 : Using join() + list comprehension The combi
4 min read
Practice Tags :
three90RightbarBannerImg