- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python Program – Convert String to matrix having K characters per row
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.
- Related Articles
- Python – Convert String to matrix having K characters per row
- Python Program to Convert Matrix to String
- Python – Convert Integer Matrix to String Matrix
- Python - To Convert Matrix to String
- Program to find string after deleting k consecutive duplicate characters in python
- Program to convert a string to zigzag string of line count k in python
- Python – Rows with K string in Matrix
- C++ program to remove row or column wise duplicates from matrix of characters
- Program to find minimum required chances to form a string with K unique characters in Python
- Convert a String into a square matrix grid of characters in C++
- Python Program to convert a list into matrix with size of each row increasing by a number
- Python program to Convert Matrix to Dictionary Value List
- Java program to convert a list of characters into a string
- C# program to convert a list of characters into a string
- Program to swap string characters pairwise in Python

Advertisements