Python: How to reverse an objects string function in python

For example, I have a class Wall (doesnt have an init)

if a = Wall()

and str(a) outputs: '#'

if i have a string containing '####'

how can i turn that string into a list, that has the name of the class object like this: [Wall(), Wall(), Wall(), Wall()]

2 answers

  • answered 2022-05-04 11:11 Peter Wood

    You can use a list comprehension with a filtering clause:

    walls = [Wall() for char in string
             if char == '#']

  • answered 2022-05-04 11:15 matszwecja

    You should make an explicit mapping dictionary that tells what each of the characters in the string is supposed to mean.

    wall = object()
    mapping = {
        "#": wall
    string = '####'
    result = [mapping[ch] for ch in string]

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum