Search code examples
pythonstringlistvariablesblit

How do I find a preexisting variable with a list of strings in Python?


How do I find a preexisting variable with a list of strings in Python?

I have a list of strings, such as:

letters = ["C", "A", "M", "P"]

and a set of preexisting variables, such as:

C = pygame.image.load("resources/menu icons/imgC.png")
A = pygame.image.load("resources/menu icons/imgA.png")
M = pygame.image.load("resources/menu icons/imgM.png")
P = pygame.image.load("resources/menu icons/imgP.png")

I am looking for a command such as:

surface.blit(letters[0])

to display the image on the screen. Can anyone help?


Solution

  • Cyber's method has the advantage of keeping your namespace more organized, but it's also nice to know about globals, with which you can do this:

    surface.blit(globals()[letters[0]])
    

    (assuming C, A, M, P are defined in the global namespace. If they are local variables, you could use vars() instead of globals().)