Python – Convert String to matrix having K characters per row

PythonServer Side ProgrammingProgramming

When it is required to convert a string to matrix having K characters per row, a method is defined that uses list comprehension, and list slicing to determine the result.

Example

Below is a demonstration of the same −

def convert_to_matrix(my_string, my_key):
   temp = [my_string[index: index + my_key] for index in range(0, len(my_string), my_key)]

   my_result = [list(element) for element in temp]

   print(my_result)

my_string = 'Python is fun'

print("The string is :")
print(my_string)

K = 7
print("The value of K is :")
print(K)

print("The result is :")
convert_to_matrix(my_string, K)

Output

The string is :
Python is fun
The value of K is :
7
The result is :
[['P', 'y', 't', 'h', 'o', 'n', ' '], ['i', 's', ' ', 'f', 'u', 'n']]

Explanation

  • A method named ‘convert_to_matrix’ is defined that takes a string and a key as parameters.

  • It uses list comprehension and list slicing to determine the output.

  • This is assigned to a variable.

  • This variable is displayed as output.

  • Outside the method, a string is defined and is displayed on the console.

  • The value for ‘key’ is defined and is displayed on the console.

  • The method is called by passing the required parameters.

  • The output is displayed on the console.

raja
Published on 08-Sep-2021 07:03:31
Advertisements