GeeksforGeeks App
Open App
Browser
Continue

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

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']]```

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.

My Personal Notes arrow_drop_up