Python Program – Convert String to matrix having K characters per row

PythonServer Side ProgrammingProgramming

When it is required to convert a string into a matrix that has ‘K’ characters per row, a method is defined that takes a string and a value for ‘K’. It uses a simple iteration, the modulus operator and the ‘append’ method.

Example

Below is a demonstration of the same −

print("Method definition begins")
def convert_my_string(my_string, my_k):

   for index in range(len(my_string)):
      if index % my_k == 0:
         sub = my_string[index:index+my_k]
         my_list = []
         for j in sub:
            my_list.append(j)
         print(' '.join(my_list))
print("Method definition ends")

my_string = "PythonCode&Learn&ObjectOriented"
print("The string is : " )
print(my_string)

K = 3
print("The value of K is ")
print(K)

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

Output

Method definition begins
Method definition ends
The string is :
PythonCode&Learn&ObjectOriented
The value of K is
3
The result is :
P y t
h o n
C o d
e & L
e a r
n & O
b j e
c t O
r i e
n t e
d
None

Explanation

  • A method is defined that takes a string and a K value as parameter, and returns as output.

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

  • The value for K is defined and displayed in the console.

  • The method is called by passing the parameters.

  • This is displayed as output on the console.

raja
Updated on 13-Sep-2021 08:19:15

Advertisements