'Python how to loop through multiple variables [duplicate]
I several variables named S1 - S6 and I want to be able to loop through each of them so I can do some string comparisons and manipution on them but I cant work out how to do it
allSeats = "1"
for x in "S" + allSeats:
print(x)
allSeats = allSeats + 1
So I want that print(x) to do is essectially just print the string stored in the variable S1 for example. Hope that makes sense I dont really know how to explain it
Solution 1:[1]
You can put S1 - S6 into a list and iterate through that:
lst = [S1, S2, S3, S4, S5, S6]
for x in lst:
print(x)
Is this what you want? I would recommend to learn the python basics first, there are some nice videos on youtube.
Solution 2:[2]
There is actually a way to do what you are trying to do within Python because it is an 'interpreted language,' you can create strings which contain code and then use the eval function to run the code.
However, you almost never want to do that. To do what you are looking for, you want to use a Python dictionary, like this:
all_seats = {
"S1": 456,
"S2": 123
}
for key, value in all_seats.items():
print(f"Seat number {key} has value {value}")
Solution 3:[3]
You can do it with eval keyword.
s1 = "seat1"
s2 = "seat2"
for i in range(1,3):
for x in eval("s"+str(i)):
print(x)
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 | Theodor Peifer |
| Solution 2 | Cargo23 |
| Solution 3 | Nop |
