Python converts string to List

Question:

a = " 23456789123456789123456789123456789123456789123456789123456789123456789123456789"

The space at the beginning of the string a is space.

Now I need a function to make the string into a list.

Here is my code:

(Board = list[list[Optional[int]]])

def stringtolist(raw_string: str) -> Board:

    list_a = list(raw_string)
    result = []
    for y in range(0, 9):
        for x in range(0, 9):
            if x == 0:
                result.append([])
            result[y].append(list_a[x + y * 9])
    print(result)

I tested this code is working, but how can I make spaces display None in the result list?

Asked By: Tyou

||

Answers:

What about using a list comprehension?

[[c if c!=' ' else None for c in a[i:i+9]] for i in range(0, len(a), 9)]

output:

[[None, '2', '3', '4', '5', '6', '7', '8', '9'],
 ['1', '2', '3', '4', '5', '6', '7', '8', '9'],
 ['1', '2', '3', '4', '5', '6', '7', '8', '9'],
 ['1', '2', '3', '4', '5', '6', '7', '8', '9'],
 ['1', '2', '3', '4', '5', '6', '7', '8', '9'],
 ['1', '2', '3', '4', '5', '6', '7', '8', '9'],
 ['1', '2', '3', '4', '5', '6', '7', '8', '9'],
 ['1', '2', '3', '4', '5', '6', '7', '8', '9'],
 ['1', '2', '3', '4', '5', '6', '7', '8', '9']]
Answered By: mozway
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.