-9

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

  • Your example code doesn't do what you think it does. You are building static strings, not variable names in the for statement. – nicomp Jul 17 '20 at 14:34
  • Why don't you write your variables as an array? That way you can loop through them. – Telmo Trooper Jul 17 '20 at 14:36
  • 1
    Does this answer your question? [How can I use a for loop to iterate through numbered variables?](https://stackoverflow.com/questions/33153564/how-can-i-use-a-for-loop-to-iterate-through-numbered-variables) – dspencer Jul 17 '20 at 14:52

3 Answers3

0

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.

Theodor Peifer
  • 3,097
  • 4
  • 17
  • 30
0

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}")
Cargo23
  • 3,064
  • 16
  • 25
0

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)
Nop
  • 1
  • 1