1

I am trying to turn a string into a variable name. I already have the variable declared and want to use it to declare another variable with it. For example I have a class named player and want to change the armor the player is wearing with this code.

gt = gettext("playerarmor", 1, 1)
for i in armorlist:
    if i == gt:
        player.armor = i

But the gettext function here:

def gettext(header, move, count):
    with open('dictionary.txt', 'r') as f:
        f = f.read()
        lines = f.split("\n")

    for i, line in enumerate(lines):
        if header in line:
            word = []
            for l in range(0, count):
                newindex = i + move
                word.append(lines[newindex+l])

            return "\n".join(word)

only returns a string which is rags and is already declared. How can I make this happen?

martineau
  • 119,623
  • 25
  • 170
  • 301
Astro
  • 33
  • 8
  • 3
    Generally you should not create variables dynamically. Use a dict (dictionary) instead. – Michael Butscher Jul 22 '22 at 22:03
  • 2
    You never ever ever should have to rely on variable names for anything in any such Python project. Surely there's a way to store and differentiate a list of objects associated with the player that doesn't rely on variable names. You're just asking for a headache and trouble. Why not use a `dict` at least if you want to have objects associated with a name? – Random Davis Jul 22 '22 at 22:04
  • Alright i'll do some research on dictionaries. Thanks for the advice everyone! – Astro Jul 22 '22 at 22:15

1 Answers1

2

strings cannot become variable names

I suggest having a dictionary with the string as the of elements and value as the value

runnerX
  • 56
  • 4
  • 3
    Strings can become (=used as) variable names (except for function local variables) but it is usually a bad idea. – Michael Butscher Jul 22 '22 at 22:05
  • 2
    @Astro Many variables in Python are stored in dictionary-like objects which can be modified to change or add variables whose names can be given as strings. So you have to deal with dictionaries anyway. – Michael Butscher Jul 22 '22 at 22:19
  • Thanks so much! Literally was a simple fix. Turned the lists I had in the for loop to dictionaries. – Astro Jul 22 '22 at 22:26