'How to insert every string character to two dimensional array

I've made two dimensional array

rows, columns = (5, 4)
table = [["" for i in range(columns)] for j in range(rows)]

now I want to insert every string character to it

string = "aaa bb cccc d eee"

I want this output : [['a', 'a', 'a', ''], ['b', 'b', '', 'c'], ['c', 'c', 'c', ''], ['d', '', 'e', 'e'], ['e', '', '', '']]

I tried something like this in many ways but it throws an error.

 for i in range(len(string)):
        table[columns][rows] = string[i]


Solution 1:[1]

With your table and string

rows, columns = (5, 4)
table = [['' for i in range(columns)] for j in range(rows)]
string = "aaa bb cccc d eee"

you can set elements of table to letters of string while looping rows of table.

str_iter = iter(string)
for row in table:
    for e, (_, row[e]) in enumerate(zip(row, str_iter)): ...

print(table)

Output

[['a', 'a', 'a', ' '],
 ['b', 'b', ' ', 'c'],
 ['c', 'c', 'c', ' '],
 ['d', ' ', 'e', 'e'],
 ['e', '', '', '']]

Solution 2:[2]

Using numpy's array.reshape and str.ljust:

import numpy as np

mystring = "aaa bb cccc d eee"
n_rows, n_columns = (5, 4)

table = np.array(list(mystring.ljust(n_rows*n_columns))).reshape(n_rows, n_columns)

print(table)
# [['a' 'a' 'a' ' ']
#  ['b' 'b' ' ' 'c']
#  ['c' 'c' 'c' ' ']
#  ['d' ' ' 'e' 'e']
#  ['e' ' ' ' ' ' ']]

Using more_itertools' grouper, ignoring the number of rows and assuming there is less than one full row of spaces to add:

from more_itertools import grouper

mystring = "aaa bb cccc d eee"
n_columns = 4

table = list(grouper(mystring, n_columns, fillvalue=' '))

print(table)
# [('a', 'a', 'a', ' '),
#  ('b', 'b', ' ', 'c'),
#  ('c', 'c', 'c', ' '),
#  ('d', ' ', 'e', 'e'),
#  ('e', ' ', ' ', ' ')]

Using more_itertools' chunked with str.ljust:

from more_itertools import chunked

mystring = "aaa bb cccc d eee"
n_rows, n_columns = 6, 4

table = list(chunked(mystring.ljust(n_rows*n_columns), n_columns))

print(table)
# [['a', 'a', 'a', ' '],
#  ['b', 'b', ' ', 'c'],
#  ['c', 'c', 'c', ' '],
#  ['d', ' ', 'e', 'e'],
#  ['e', ' ', ' ', ' '],
#  [' ', ' ', ' ', ' ']]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2