Open In App

Python – Convert String to matrix having K characters per row

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

Given a String, convert it to Matrix, having K characters in each row.

Input : test_str = ‘GeeksforGeeks is best’, K = 7 
Output : [[‘G’, ‘e’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’], [‘r’, ‘G’, ‘e’, ‘e’, ‘k’, ‘s’, ‘ ‘], [‘i’, ‘s’, ‘ ‘, ‘b’, ‘e’, ‘s’, ‘t’]] 
Explanation : Each character is assigned to 7 element row in matrix.

Input : test_str = ‘GeeksforGeeks ‘, K = 7 
Output : [[‘G’, ‘e’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’], [‘r’, ‘G’, ‘e’, ‘e’, ‘k’, ‘s’, ‘ ‘]] 
Explanation : Each character is assigned to 7 element row in matrix. 

Method #1 : Using list comprehension + slicing

The combination of the above functionalities can be used to solve this problem. In this, we first extract separate strings for each row using slicing and list comprehension. Then convert each string to a character list using list().

Python3




# Python3 code to demonstrate working of
# Convert String to K characters row Matrix
# Using list comprehension + slicing
 
 
# Function to Convert String
# to K characters row Matrix
def convertToMatrix(test_str, K):
    # slicing strings
    temp = [test_str[idx: idx + K] for idx in range(0, len(test_str), K)]
 
    # conversion to list of characters
    res = [list(ele) for ele in temp]
 
    # printing result
    print("The converted Matrix : " + str(res))
 
 
# Driver Code   
# initializing string
input_str = 'GeeksforGeeks is best'
 
# printing original string
print("The original string is : " + str(input_str))
 
# initializing K
K = 7
 
# calling the function
convertToMatrix(input_str, K)


Output

The original string is : GeeksforGeeks is best
The converted Matrix : [['G', 'e', 'e', 'k', 's', 'f', 'o'], ['r', 'G', 'e', 'e', 'k', 's', ' '], ['i', 's', ' ', 'b', 'e', 's', 't']]

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

Method #2 : Using list comprehension + map() + slicing

This is yet another way in which this task can be performed. In this, we perform task in similar way as above functions, difference being conversion to list is done using map() rather than list comprehension.

Python3




# Python3 code to demonstrate working of
# Convert String to K characters row Matrix
# Using list comprehension + map() + slicing
 
 
# Function to Convert String
# to K characters row Matrix
def convertToMatrix(test_str, K):
    # slicing strings
    temp = [test_str[idx: idx + K] for idx in range(0, len(test_str), K)]
 
    # conversion using map
    res = list(map(lambda ele: list(ele), temp))
 
    # printing result
    print("The converted Matrix : " + str(res))
 
 
# Driver Code
# initializing string
input_str = 'GeeksforGeeks is best'
 
# printing original string
print("The original string is : " + str(input_str))
 
# initializing K
K = 7
 
# calling the function
convertToMatrix(input_str, K)


Output

The original string is : GeeksforGeeks is best
The converted Matrix : [['G', 'e', 'e', 'k', 's', 'f', 'o'], ['r', 'G', 'e', 'e', 'k', 's', ' '], ['i', 's', ' ', 'b', 'e', 's', 't']]

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

Method 3: Using simple for loop

Slice the input string into K characters rows using two nested for loops, convert each row into a list of characters, and print the resulting matrix.

  • Create an empty list called rows to hold the rows of the matrix.
  • Use a for loop to iterate over the indices of the string test_str, incrementing by K at each step. This will split the string into rows of K characters.
    • For each row, create an empty list called row to hold the characters in the row.
      • Use another for loop to iterate over the indices of the current row, incrementing by 1 at each step.
        • If the index i+j is within the bounds of the string test_str, append the character at that index to the current row.
          • Append the current row to the list of rows.
    • After all rows have been processed, print the resulting matrix by converting each row to a string and enclosing them in square brackets, separated by commas.

Below is the implementation of the above approach:

Python3




# Function to Convert String to K characters row Matrix
def convertToMatrix(test_str, K):
    rows = []
    for i in range(0, len(test_str), K):
        row = []
        for j in range(K):
            if i+j < len(test_str):
                row.append(test_str[i+j])
        rows.append(row)
    # printing result
    print("The converted Matrix : " + str(rows))
 
 
# Driver Code   
# initializing string
input_str = 'GeeksforGeeks is best'
 
# printing original string
print("The original string is : " + str(input_str))
 
# initializing K
K = 7
 
# calling the function
convertToMatrix(input_str, K)


Output

The original string is : GeeksforGeeks is best
The converted Matrix : [['G', 'e', 'e', 'k', 's', 'f', 'o'], ['r', 'G', 'e', 'e', 'k', 's', ' '], ['i', 's', ' ', 'b', 'e', 's', 't']]

Time Complexity: O(NK), where N is the length of the input string.
Auxiliary Space: O(N)

Method #4: Using numpy.reshape()

You can also use the numpy.reshape() function to convert the string to a matrix of K columns. Here’s how you can do it:

Step by step approach of the program:

  1. Import the numpy module as np.
  2. Define a function called convertToMatrix that takes two arguments: test_str, which is the input string, and K, which is the number of columns in the matrix.
  3. Calculate the number of spaces needed to pad the input string so that its length is a multiple of K. This is done by subtracting the length of the input string modulo K from K.
  4. Append the calculated number of spaces to the input string.
  5. Convert the input string to a 1D numpy array by calling the list() function on the input string to convert it to a list of characters, and then passing the list to the np.array() function.
  6. Reshape the 1D numpy array to a 2D matrix with K columns by calling the reshape() function on the numpy array and passing in the number of rows (-1, which means that numpy will automatically determine the number of rows) and the number of columns (K).
  7. Print the resulting matrix by calling the print() function and passing in a string that contains the string representation of the matrix.
  8. Define the main function called __main__.
  9. Define the input string called input_str.
  10. Print the original input string by calling the print() function and passing in a string that contains the string representation of the input string.
  11. Define the number of columns called K.
  12. Call the convertToMatrix function with the input string and the number of columns as arguments.
  13. End the program.

Python3




import numpy as np
 
def convertToMatrix(test_str, K):
    # Pad the input string with spaces so that its length is a multiple of K
    num_spaces = K - len(test_str) % K
    test_str += ' ' * num_spaces
     
    # Convert the string to a 1D numpy array
    arr = np.array(list(test_str))
     
    # Reshape the array to a 2D matrix with K columns
    rows = arr.reshape(-1, K)
     
    # printing result
    print("The converted Matrix : " + str(rows))
 
# Driver Code   
# initializing string
input_str = 'GeeksforGeeks is best'
 
# printing original string
print("The original string is : " + str(input_str))
 
# initializing K
K = 7
 
# calling the function
convertToMatrix(input_str, K)


OUTPUT:

The original string is : GeeksforGeeks is best
The converted Matrix : [['G' 'e' 'e' 'k' 's' 'f' 'o']
['r' 'G' 'e' 'e' 'k' 's' ' ']
['i' 's' ' ' 'b' 'e' 's' 't']
[' ' ' ' ' ' ' ' ' ' ' ' ' ']]

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. This is because we need to create a numpy array of length N to store the characters in the input string.

Method #5: Using itertools.islice()

Step-by-step approach:

  • The convertToMatrix function takes two arguments – a string test_str and an integer K. The goal of this function is to convert the input string into a 2D matrix where each row has K characters.
  • Inside the function, the islice function from the itertools module is used to slice the input string into chunks of K characters. This is done using a list comprehension that loops through the range 0 to len(test_str) with a step size of K. For each index i, islice is used to get a slice of the input string starting from index i and ending at index i+K. This slice is then converted to a list using the list function and stored in the temp list.
  • Finally, the temp list is printed to display the resulting 2D matrix.
  • In the Driver Code section, an input string input_str and an integer K are initialized.
  • The original string is printed to the console using the print function and the str function to convert the input string to a string.
  • The convertToMatrix function is called with the input_str and K arguments.
  • When the function is called, it converts the input string into a 2D matrix using the islice function and the steps outlined above.
  • The resulting 2D matrix is printed to the console.

Below is the implementation of the above approach:

Python3




import itertools
 
def convertToMatrix(test_str, K):
    # using islice to slice the string
    temp = [list(itertools.islice(test_str, i, i+K)) for i in range(0, len(test_str), K)]
 
    # printing result
    print("The converted Matrix : " + str(temp))
 
# Driver Code
# initializing string
input_str = 'GeeksforGeeks is best'
 
# printing original string
print("The original string is : " + str(input_str))
 
# initializing K
K = 7
 
# calling the function
convertToMatrix(input_str, K)


Output

The original string is : GeeksforGeeks is best
The converted Matrix : [['G', 'e', 'e', 'k', 's', 'f', 'o'], ['r', 'G', 'e', 'e', 'k', 's', ' '], ['i', 's', ' ', 'b', 'e', 's', 't']]

Time complexity: O(n), where n is the length of the input string.
Auxiliary space: O(n/K), as we are storing n/K chunks of size K in a 2D list.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads