Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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, we can use string slicing and list comprehension. This technique is useful for formatting text data into fixed-width rows for display or processing.
Method 1: Using String Slicing and List Comprehension
This approach creates a matrix by slicing the string into chunks of K characters ?
def convert_string_to_matrix(text, k):
matrix = []
for i in range(0, len(text), k):
row = list(text[i:i+k])
matrix.append(row)
return matrix
# Example usage
my_string = "PythonCode&Learn&ObjectOriented"
print("The string is:")
print(my_string)
K = 3
print(f"\nThe value of K is: {K}")
result = convert_string_to_matrix(my_string, K)
print("\nThe matrix is:")
for row in result:
print(row)
The string is: PythonCode&Learn&ObjectOriented The value of K is: 3 The matrix 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']
Method 2: Using List Comprehension
A more concise approach using list comprehension for the same result ?
def convert_string_compact(text, k):
return [list(text[i:i+k]) for i in range(0, len(text), k)]
# Example usage
my_string = "HelloWorld"
K = 4
print("Original string:", my_string)
print(f"K value: {K}")
matrix = convert_string_compact(my_string, K)
print("\nResulting matrix:")
for i, row in enumerate(matrix):
print(f"Row {i}: {row}")
Original string: HelloWorld K value: 4 Resulting matrix: Row 0: ['H', 'e', 'l', 'l'] Row 1: ['o', 'W', 'o', 'r'] Row 2: ['l', 'd']
Method 3: Displaying as Formatted Output
To display the matrix in a more readable format with spaces between characters ?
def display_formatted_matrix(text, k):
print("Formatted matrix:")
for i in range(0, len(text), k):
row_chars = text[i:i+k]
formatted_row = ' '.join(row_chars)
print(formatted_row)
# Example usage
my_string = "DataScience"
K = 3
print("Original string:", my_string)
print(f"Characters per row: {K}")
print()
display_formatted_matrix(my_string, K)
Original string: DataScience Characters per row: 3 Formatted matrix: D a t a S c i e n c e
Comparison
| Method | Output Type | Best For |
|---|---|---|
| String Slicing with Loop | List of lists | Further processing |
| List Comprehension | List of lists | Concise code |
| Formatted Display | Printed output | Visual representation |
Conclusion
Converting a string to a matrix with K characters per row can be efficiently accomplished using string slicing. Use list comprehension for concise code or formatted display for visual output.
Advertisements
