Search code examples
pythonstringlistpygamefilenames

Python, pygame - Loading image filename from string variable in a list?


I'm a beginning pygamer trying to upgrade a text game I wrote to a gui game.

animals = {dog: "Dog" 4 "Bone",
    cat: "Cat" 4 "Yarn",
    parrot: "Parrot" 2 "Bell"}

pet = animals[dog].split()

pet.append(pygame.image.load('//home/me/Desktop/Python/'+pet[0]+'.png')

If I were to input the above code and try to run it I get:

pygame.error: Couldn't open //home/me/Desktop/Python/"Dog".png

How do I use a string variable from a list to load a file without getting quotes added to the file name?


Solution

  • Just replace " in pet[0] with an empty string.

    pet.append(pygame.image.load('//home/me/Desktop/Python/'+pet[0].replace('"', "")+'.png')
    

    Example:

    >>> animals = {'dog': '"Dog" 4 "Bone"',
        'cat': '"Cat" 4 "Yarn"',
        'parrot': '"Parrot" 2 "Bell"'}
    >>> pet = animals['dog'].split()
    >>> '//home/me/Desktop/Python/'+pet[0].replace('"', "")+'.png'
    '//home/me/Desktop/Python/Dog.png'