0

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()]

4
  • Are there other object types you want to create or just Wall objects? Commented May 4, 2022 at 11:10
  • What if the input string is 'a#b#c'? Commented May 4, 2022 at 11:10
  • 1
    Do you have an exhaustive list of strings corresponding to classes? With the limited examples you give, there are just too many possible options, many of which won't work for your use case. We need more details, more evidence of effort, and a minimal reproducible example that's more than just one fairly unclear example. Commented May 4, 2022 at 11:11
  • 1
    "...that has the name of the class object": what does that mean? Do you mean the list elements should be strings having that name? Commented May 4, 2022 at 11:15

2 Answers 2

1

You can use a list comprehension with a filtering clause:

walls = [Wall() for char in string
         if char == '#']
Sign up to request clarification or add additional context in comments.

Comments

0

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]

4 Comments

I like this mapping answer, it's more flexible.
Won't all the objects be the same object?
@PeterWood they will, but the question was too poorly phrased for me to know whether that is desired behaviour or not.
You should ask for clarification and help new users make better questions.

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.