-2

Basically, I have this:

ls = [
    '###',
    '# a',
    '#b#'
]

and want it to be like:

ls = [
    ['#', '#', '#'], 
    ['#', ' ', 'a'],
    ['#', 'b', '#']
]

Anyone could help me out?

  • 1
    What have you tried already? (Hint, this is string handling 101.) – S3DEV Aug 12 '21 at 19:44
  • 1
    Does this answer your question? [How can I turn a string into a list in Python?](https://stackoverflow.com/questions/7522533/how-can-i-turn-a-string-into-a-list-in-python) – Jab Aug 12 '21 at 19:55

3 Answers3

0

Just convert each string to a list in a list comprehension

>>> [list(s) for s in ls]
[['#', '#', '#'], ['#', ' ', 'a'], ['#', 'b', '#']]
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
0

By using a list comprehension you can loop through your list and apply some operation on your list items. By putting these items into the list operator you turn an iterable into a list. Because a string is basically a iterable of characters you can convert it into a list of characters with list.

ls = [
    '###',
    '# a',
    '#b#'
]

[list(x) for x in ls]
>> [['#', '#', '#'], ['#', ' ', 'a'], ['#', 'b', '#']]
chatax
  • 990
  • 3
  • 17
0
print(list(map(list, ls)))  # [['#', '#', '#'], ['#', ' ', 'a'], ['#', 'b', '#']]
Алексей Р
  • 7,507
  • 2
  • 7
  • 18