'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()]
Solution 1:[1]
You can use a list comprehension with a filtering clause:
walls = [Wall() for char in string
if char == '#']
Solution 2:[2]
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]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Peter Wood |
| Solution 2 | matszwecja |
