Home > Mobile >  Storing list of strings that have a format variable
Storing list of strings that have a format variable

Time:12-29

I have a long list of strings (about 250), and some include formating that requires a variable. Right now, when I keep the list with declared variables in my main script it has no issues, but the list is eating up a lot of lines. So, I would like to store and then read the list into the script using variables listed there; however, I'm getting an undeclared variable error when doing so.

user = "John"
grade = "8th"
teacher = "Ms. Smith"

messages = [
            "Welcome {}".format(user), 
            "You are in {} grade".format(grade),
            "Your teacher is {}.".format(teacher)
           ]

So the above is a very over simpled example, but I've tried putting the list of strings in a separate python file named homeroom and importing it over - from homeroom import messages - but seems the variable is an issue even when I have the matching variable in the main script. Also, I have tried using JSON dumps and loads and I get the same error.

CodePudding user response:

you did not provide any code for importing your other python file but i assumed you have a dictionary of values in this file.

i provide a little snippet of how you can use a "remote" Dictionary. If this is the only content in this file i would recommend using a Yml reader or similar to parse into an object.

assumed main.py import homeroom

messages = [
            "Welcome {}".format(homeroom.messagevars["var1"])
           ]


print(messages)

outputs: Welcome Peter

homeroom.py

messagevars = {
    "var1": "Peter",
}

CodePudding user response:

I would advise you to create a function that stores your list when you initialize it and where you give those variables as parameters.

With this method, you can store your list without predefined variables and when you need it just call the function with your variables.

  • Related