Python - Double Split String to Matrix
Last Updated :
12 Apr, 2023
Given a String, perform the double split, 1st for rows, and next for individual elements so that the given string can be converted to a matrix.
Examples:
Input : test_str = 'Gfg,best*for,all*geeks,and,CS', row_splt = "*", ele_splt = ","
Output : [['Gfg', 'best'], ['for', 'all'], ['geeks', 'and', 'CS']]
Explanation : String split by rows, and elements by respective delims.
Input : test_str = 'Gfg!best*for!all*geeks!and!CS', row_splt = "*", ele_splt = "!"
Output : [['Gfg', 'best'], ['for', 'all'], ['geeks', 'and', 'CS']]
Explanation : String split by rows, and elements by respective delims.
Method #1 : Using split() + loop
In this, 1st split() is used to construct rows of Matrix, and then nested split() to get separation between individual elements.
Step by step approach :
- We start by importing the necessary Python modules and initializing the string variable test_str to the value 'Gfg,best#for,all#geeks,and,CS'.
- We print the original string using the print() function and string concatenation.
- We initialize the variables row_splt and ele_splt to the characters '#' and ',' respectively.
- We use the split() function to split the string test_str into a list of substrings using the row_splt character as the delimiter. This returns a list of three substrings: 'Gfg,best', 'for,all', and 'geeks,and,CS'. We store this list in the variable temp.
- We create an empty list called res.
- We loop through each element ele in the list temp.
- For each ele, we split it into a list of substrings using the ele_splt character as the delimiter. For example, the first iteration of the loop splits the string 'Gfg,best' into the list ['Gfg', 'best'].
- We append the resulting list to the res list.
- After the loop has finished executing, the res list contains three lists, each of which represents a row in the matrix.
- We print the resulting matrix by converting the res list to a string using the str() function and concatenating it with a message.
Python3
# Python3 code to demonstrate working of
# Double Split String to Matrix
# Using split() + loop
# initializing string
test_str = 'Gfg,best#for,all#geeks,and,CS'
# printing original string
print("The original string is : " + str(test_str))
# initializing row split char
row_splt = "#"
# initializing element split char
ele_splt = ","
# split for rows
temp = test_str.split(row_splt)
res = []
for ele in temp:
# split for elements
res.append(ele.split(ele_splt))
# printing result
print("String after Matrix conversion : " + str(res))
OutputThe original string is : Gfg,best#for,all#geeks,and,CS
String after Matrix conversion : [['Gfg', 'best'], ['for', 'all'], ['geeks', 'and', 'CS']]
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #2 : Using list comprehension + split()
This is yet another way in which this task can be performed. In this, we use a similar process, but one-liner to solve the problem.
Python3
# Python3 code to demonstrate working of
# Double Split String to Matrix
# Using list comprehension + split()
# initializing string
test_str = 'Gfg,best#for,all#geeks,and,CS'
# printing original string
print("The original string is : " + str(test_str))
# initializing row split char
row_splt = "#"
# initializing element split char
ele_splt = ","
# split for rows
temp = test_str.split(row_splt)
# using list comprehension as shorthand
res = [ele.split(ele_splt) for ele in temp]
# printing result
print("String after Matrix conversion : " + str(res))
OutputThe original string is : Gfg,best#for,all#geeks,and,CS
String after Matrix conversion : [['Gfg', 'best'], ['for', 'all'], ['geeks', 'and', 'CS']]
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #4: Using regular expressions
In the above code, we first split the string into rows and elements using the re.split() method and the row_splt and ele_splt delimiters. Then, we create a matrix out of the resulting list of lists.
Python3
# Python3 code to demonstrate working of
# Double Split String to Matrix
# Using regular expressions
import re
# initializing string
test_str = 'Gfg,best#for,all#geeks,and,CS'
# printing original string
print("The original string is : " + str(test_str))
# initializing row split char
row_splt = "#"
# initializing element split char
ele_splt = ","
# split for rows and elements using regular expressions
res = [re.split(ele_splt, x) for x in re.split(row_splt, test_str)]
# printing result
print("String after Matrix conversion : " + str(res))
OutputThe original string is : Gfg,best#for,all#geeks,and,CS
String after Matrix conversion : [['Gfg', 'best'], ['for', 'all'], ['geeks', 'and', 'CS']]
Time complexity: O(n*m), where n is the number of rows and m is the number of elements in each row.
Auxiliary space: O(n*m), as we need to create a list of lists to store the resulting matrix.
Method #4: Using map() + lambda function
Here is an alternative approach using the map() function and lambda function to split the string into rows and elements.
Steps:
- Initialize the string and the row and element split characters.
- Use the map() function with lambda function to split the string into rows and then split each row into elements.
- Convert the resulting map object into a list and print the output.
Python3
# Python3 code to demonstrate working of
# Double Split String to Matrix
# Using map() + lambda function
# initializing string
test_str = 'Gfg,best#for,all#geeks,and,CS'
# printing original string
print("The original string is : " + str(test_str))
# initializing row split char
row_splt = "#"
# initializing element split char
ele_splt = ","
# splitting string into matrix using map() and lambda function
res = list(map(lambda x: x.split(ele_splt), test_str.split(row_splt)))
# printing result
print("String after Matrix conversion : " + str(res))
OutputThe original string is : Gfg,best#for,all#geeks,and,CS
String after Matrix conversion : [['Gfg', 'best'], ['for', 'all'], ['geeks', 'and', 'CS']]
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 (for storing the output list).
Method #5: Using NumPy
The program imports the NumPy library using import numpy as np.
The program initializes a string called test_str with the value 'Gfg,best#for,all#geeks,and,CS'.
The program then prints the original string using the print() function and string concatenation.
The program initializes a variable called row_splt with the value #, and a variable called ele_splt with the value ,. These variables represent the characters used to split the string into rows and elements.
The program splits the string into a list of rows using the row_splt character, and then splits each row into a list of elements using the ele_splt character, using a nested list comprehension.
The program creates a NumPy array from the resulting list using the np.array() function.
The program then prints the resulting NumPy array using the print() function.
Python3
import numpy as np
# initializing string
test_str = 'Gfg,best#for,all#geeks,and,CS'
# printing original string
print("The original string is : " + str(test_str))
# initializing row split char
row_splt = "#"
# initializing element split char
ele_splt = ","
# splitting string into matrix using NumPy
rows = [row.split(ele_splt) for row in test_str.split(row_splt)]
max_len = max(len(row) for row in rows)
rows_padded = [row + [""]*(max_len - len(row)) for row in rows]
res = np.array(rows_padded)
# printing result
print("String after Matrix conversion : " + str(res))
OUTPUT:
The original string is : Gfg,best#for,all#geeks,and,CS
String after Matrix conversion : [['Gfg' 'best' '']
['for' 'all' '']
['geeks' 'and' 'CS']]
Time complexity: O(n^2) for both creating the list of rows and elements and for converting the list to a NumPy array.
Auxiliary space: O(n^2) for the list of rows and elements, and O(n^2) for the NumPy array.
Similar Reads
Python - Combine Strings to Matrix
Sometimes while working with data, we can receive separate data in the form of strings and we need to compile them into Matrix for its further use. This can have applications in many domains. Let's discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + split
4 min read
Python | Delimited String List to String Matrix
Sometimes, while working with Python strings, we can have problem in which we need to convert String list which have strings that are joined by deliminator to String Matrix by separation by deliminator. Lets discuss certain ways in which this task can be performed. Method #1 : Using loop + split() T
5 min read
Python | Split flatten String List
Sometimes, while working with Python Strings, we can have problem in which we need to perform the split of strings on a particular deliminator. In this, we might need to flatten this to a single String List. Let's discuss certain ways in which this task can be performed. Method #1 : Using list compr
7 min read
Python - Split Strings on Prefix Occurrence
Given a list of Strings, perform string split on the occurrence of prefix. Input : test_list = ["geeksforgeeks", "best", "geeks", "and"], pref = "geek" Output : [['geeksforgeeks', 'best'], ['geeks', 'and']] Explanation : At occurrence of string "geeks" split is performed. Input : test_list = ["good"
7 min read
Split a String by a Delimiter in Python
In Python Programming, the split() method is used to split a string into a list of substrings which is based on the specified delimiter. This method takes the delimiter as an argument and returns the list of substrings. Along with this method, we can use various approaches wot split a string by the
2 min read
Convert Character Matrix to single String - Python
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 LoopWe 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
2 min read
Python | Exceptional Split in String
Sometimes, while working with Strings, we may need to perform the split operation. The straightforward split is easy. But sometimes, we may have a problem in which we need to perform split on certain characters but have exceptions. This discusses split on comma, with the exception that comma should
4 min read
Python | K Character Split String
The problems and at the same time applications of list splitting is quite common while working with python strings. Some characters are usually tend to ignore in the use cases. But sometimes, we might not need to omit those characters but include them in our programming output. Letâs discuss certain
4 min read
Python | Splitting operators in String
Sometimes we have a source string to have certain mathematical statement for computations and we need to split both the numbers and operators as a list of individual elements. Let's discuss certain ways in which this problem can be performed. Method #1 : Using re.split() This task can be solved usin
7 min read
Python - Splitting Text and Number in string
Given a string containing both letters and numbers, the task is to separate the text (letters) and the numbers into two separate outputs. For example, if the input is "abc123", the output should be "abc" and "123". Let's discuss various ways in which we can achieve this in Python.Using for loopThis
3 min read