- 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 – Convert String to matrix having K characters per row
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.

Advertisements