Is there a way to enter all the variable names with code instead of by hand?

Hey everyone!
I just came across the Python introduction lesson on concatenation, and one of the exercises looks like this:

string1 = "The wind, "
string2 = "which had hitherto carried us along with amazing rapidity, "
string3 = "sank at sunset to a light breeze; "
string4 = "the soft air just ruffled the water and "
string5 = "caused a pleasant motion among the trees as we approached the shore, "
string6 = "from which it wafted the most delightful scent of flowers and hay."

# Define message below:

I know that the answer is something like

message = (string1+string2+string3+string4+string5+string6)

Being a massive Excel user, I never liked re-writing the same thing more than once (“string1”, “string2”, etc), so I was wondering: is there a more elegant way to call multiple variables whose names contain a series of integrals?
Something like “print all the variables that contain “string” + all consecutive integrals, starting with 1, for as long as such variables exist”.

Pretty sure I can get the succession of integrals with a “while” loop, but I’m stuck when it comes to assembling a variable’s name with strings of text and numbers (like using “indirect” in excel). Do you guys know if that’s possible?

Building variable names doesn’t work.

A variable is not a string, but rather a sequence of characters not designated to be something else (such as def or max). If you try to designate a string as a variable (I.e., put it on the left side of an assignment statement), you will raise an error.

Have you covered lists yet? I would put the strings in a list, then:

final_str = ''  # empty string
    for element in str_lst:
        final_str += element

Edit: you’ll need to insert spaces after element, above, since concatention (+) does not.

1 Like