How to convert a matrix of numbers to a string in Python

3 Answers

0 votes
def convert_matrix_to_string(matrix):
    sizesarr = [0] * len(matrix[0])

    for row in matrix:
        for i, val in enumerate(row):
            str_val = str(val)
            if sizesarr[i] < len(str_val):
                sizesarr[i] = len(str_val)

    result = "\n".join(
        " ".join(str(val).ljust(sizesarr[i]) for i, val in enumerate(row))
        for row in matrix
    )

    return result.strip()

matrix = [
    [4, 7, 9, 18, 29, 0],
    [1, 9, 18, 99, 4, 3],
    [9, 17, 89, 2, 7, 5],
    [19, 49, 6, 1, 9, 8],
    [29, 4, 7, 9, 18, 6]
]

str_matrix = convert_matrix_to_string(matrix)

print(str_matrix)



'''
run:

4  7  9  18 29 0
1  9  18 99 4  3
9  17 89 2  7  5
19 49 6  1  9  8
29 4  7  9  18 6

'''

 



answered May 24, 2025 by avibootz
0 votes
matrix = [
    [4, 7, 9, 18, 29, 0],
    [1, 9, 18, 99, 4, 3],
    [9, 17, 89, 2, 7, 5],
    [19, 49, 6, 1, 9, 8],
    [29, 4, 7, 9, 18, 6]
]

matrix_string = " ".join([" ".join(map(str, row)) for row in matrix])

print(matrix_string)

 
 
'''
run:
 
4 7 9 18 29 0 1 9 18 99 4 3 9 17 89 2 7 5 19 49 6 1 9 8 29 4 7 9 18 6
 
'''

 



answered Jan 9 by avibootz
0 votes
matrix = [
    [4, 7, 9, 18, 29, 0],
    [1, 9, 18, 99, 4, 3],
    [9, 17, 89, 2, 7, 5],
    [19, 49, 6, 1, 9, 8],
    [29, 4, 7, 9, 18, 6]
]

matrix_string = "\n".join([" ".join(map(str, row)) for row in matrix])

print(matrix_string)

 
 
'''
run:
 
4 7 9 18 29 0
1 9 18 99 4 3
9 17 89 2 7 5
19 49 6 1 9 8
29 4 7 9 18 6
 
'''

 



answered Jan 9 by avibootz
...