Is there a way to sum different declared string variables by using their suffix number as iterator?

Viewed 133

I don't want to sum manually each declared string variable.

word1 = "How"
word2 = "do"
word3 = "you"
word4 = "like"
word5 = "Python"
word6 = "so"
word7 = "far?"
totalword=word1+" "+word2+" "+word3+" "+word4+" "+word5+" "+word6+" "+word7
print(totalword)
4 Answers

You can use this:

word1 = "How"
word2 = "do"
word3 = "you"
word4 = "like"
word5 = "Python"
word6 = "so"
word7 = "far?"

res = ' '.join([globals()[x] for x in globals() if 'word' in x])
print(res)

# How do you like Python so far?

Though, it's a bad practice.

Additionally, you can use regex to state what kind of global variables you are interested in, for example having a number between n-m and so on.

You may can try something like that with the variable in a table

word1 = "How"
word2 = "do"
word3 = "you"
word4 = "like"
word5 = "Python"
word6 = "so"
word7 = "far?"
words = [word1,word2,word3,word4,word5,word6,word7]
totalword = ""
for _ in range(len(words)):
    totalword += words[_]+" "
print(totalword)

There's way but not so pythonic:

word1 = "How"
word2 = "do"
word3 = "you"
word4 = "like"
word5 = "Python"
word6 = "so"
word7 = "far?"

for i in range(7):
    totalword += globals().get('word' + i)

This is not ideal, but it should work.

word1 = "How"
word2 = "do"
word3 = "you"
word4 = "like"
word5 = "Python"
word6 = "so"
word7 = "far?"

mask = "word"

final = " ".join([eval(mask+str(x)) for x in range(1,8)])
print(final)
Related