Python - Convert String to matrix having K characters per row

Python - Convert String to matrix having K characters per row

In this tutorial, we will learn how to convert a string into a matrix (2D list) where each row has K characters.

Objective:

Convert a given string into a 2D list (matrix) where each row contains K characters.

For Example: Given the string:

string = "thisisamatrix" 

If K=4, then the conversion should produce:

[ ['t', 'h', 'i', 's'], ['i', 's', 'a', 'm'], ['a', 't', 'r', 'i'], ['x'] ] 

Step-by-step Solution:

1. Initialize an Empty List:

Start by initializing an empty list to store the rows (sublists).

matrix = [] 

2. Convert the String to a Matrix:

Iterate over the string with steps of size K and for each step, extract the K characters, convert them into a list and append to the matrix.

for i in range(0, len(string), K): row = list(string[i:i+K]) matrix.append(row) 

Complete Code:

Here's the complete code to convert a string into a matrix with K characters per row:

def string_to_matrix(string, K): matrix = [] for i in range(0, len(string), K): row = list(string[i:i+K]) matrix.append(row) return matrix # Sample string string = "thisisamatrix" K = 4 # Convert the string to matrix result_matrix = string_to_matrix(string, K) for row in result_matrix: print(row) 

When executed, the code will produce:

['t', 'h', 'i', 's'] ['i', 's', 'a', 'm'] ['a', 't', 'r', 'i'] ['x'] 

Through this tutorial, you've learned how to efficiently convert a string into a 2D matrix with a specified number of characters per row using Python. This transformation can be useful for tasks such as text processing, visualization, or data structuring.


More Tags

apache-storm c99 geopandas eslint uninstallation azure-databricks notifyicon http-put permissions uikit

More Programming Guides

Other Guides

More Programming Examples