1

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]
2
  • Please add the error message and what is unclear about it. Commented Feb 16, 2022 at 12:10
  • 1
    please don't use 'list' as variable. it's a bad practice. also you're calling kolumns not columns. Commented Feb 16, 2022 at 12:11

3 Answers 3

2
rows, columns = (5, 4)
table = [["" for i in range(columns)]for j in range(rows)]
string = "aaa bb cccc d eee"
for i in range(len(string)):
    table[i // columns][i % columns] = string[i]
print(table)
Sign up to request clarification or add additional context in comments.

2 Comments

str ? Are you sure you want to use that as a variable name?
fair point. @OlvinRoght missed it. my bad
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', '', '', '']]

Comments

0

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', ' ', ' ', ' '],
#  [' ', ' ', ' ', ' ']]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.