0

In python if I have a series of lists such as:

room1 = [1, 0, 1, 1]
room2 = [1, 0, 0, 1]
room3 = [0, 0, 1, 1]

Then I have a integer and string such as:

location = 2
type = "room"

How can I combine the string from the variable type and the integer from location to select the relevant list and then use the value from that position in the list. For example something like this:

room2 = [1, 0, 0, 1]
location = 2
type = "room"
currentPos = type + location

print "%s" % currentPos[location]

If I combine type and location I get an error as ones a string and the others an integer. If I change location to be a string and combine both strings Python will print the currentPos output just as a string and I can't then use location to select the list value as this would require an integer.

location = "2"
type = "room"
currentPos = type + location
print "%s" %  currentPos

>>room

Is there a way to use a string from a variable and have python use the string output to explicitly select the name of another variable?

thal0k
  • 35
  • 3
  • 10

1 Answers1

-1
currentPos = type + str(location)

Or

currentPos = '%s%d' % (type, location)

Or

currentPos = '{:s}{:d}'.format(type, location)
CDspace
  • 2,639
  • 18
  • 30
  • 36
phd
  • 82,685
  • 13
  • 120
  • 165
  • Thanks for the information. I've rewritten my code based upon the above and its now functioning. – thal0k May 25 '17 at 23:45