-1

In Python 3, is there a way to concatenate a string/variable to a(nother) variable?

Say I have a some variables with similar names (for simplicity sake, they are variable; in actuality, I want to do it with class & objects):

var1 = 'Hello'
var2 = 'Greetings'

The user inputs a number, and the script prints using else if statements:

choice = input("Please select a number (1-2) >")

if choice = 1:
     print(var1)
elif choice = 2:
     print(var2)

But what I want to do is print directly without having to use else if/ switch statements/dictionaries etc. I want it so it prints(var+choice), where choice would concatenate to var, so if choice = 1, it would be print(var1); and if choice = 3, it would print(var3) (which would give an error, undefined variable).

If there isn't a way to do this, what is the cleanest way to print a choice of variables that have similar names?

  • Can you expand on why you don't want to ues a dict? They're build for that sort of thing – Pengman Sep 15 '20 at 10:18
  • 1
    Use a list: `vars = [var1, var2]` and then access with user's input: `print(vars[choice-1])`. If there is no such variable it will throw an IndexError – Tomerikoo Sep 15 '20 at 10:20
  • Welcome here. You can use the string array for this. Just store data in a string array and use choice as index to print – Imran Sep 15 '20 at 10:21
  • 1
    Does this answer your question? [How do I create a variable number of variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables) – mkrieger1 Sep 15 '20 at 10:22
  • The question and code was a simplified example of what I want to actually do. The variables in my code are objects in a class, so: var1 = Variable ('Hello') var2 = Variable ('Greetings') And then from choice, I want it to execute some other codes (we'll use print as an example): print(var + choice) That's why I can't use lists or dictionaries. Sorry for the confusion, I suppose I shouldn't have simplified the question. – tester123123 Sep 15 '20 at 10:31
  • 1
    This still doesn't explain why you can't use a list or dict... Are you aware that you can do `vars = [Variable("Greetings"), Variable("Hello")]`? – Tomerikoo Sep 15 '20 at 10:35
  • I had no idea you could do that. That solves everything- thanks! p.s I'm new to programming and rely on explanations on the interweb. – tester123123 Sep 15 '20 at 10:44
  • 1
    Well a list is just a container for other objects... No restriction on what those objects are. They can even be more lists! Good luck with your learning. I would suggest that you go over the [official Python Tutorial](https://docs.python.org/3/tutorial/index.html), use [pythontutor](http://www.pythontutor.com/visualize.html#mode=edit) to help you understand your own code, and finally read about [ask] when you encounter problems with your code and want to ask here – Tomerikoo Sep 15 '20 at 11:07

3 Answers3

0

In this particular case may use a list of variables and then simply print the indexed variable.

var = ['Hello', 'Greetings']
...
print(var[choice-1]) # since python is 0-indexed
0

Not a good practice, but you can use eval:

print(eval('var'+str(choice)))
Binyamin Even
  • 3,318
  • 1
  • 18
  • 45
0

Using globals() to dynamically get variable values

The globals function returns a dictionary of variables in module scope so you could get var1 or var2 with

selected_greeting = globals()[f"var{choice}"] 

See the linked docs for caveats on which variables you'll have access to.

Further reading: getattr will let you dynamically get variable values of other objects.

Using a dict or list

We end up accessing var1 and var2 through a dict, so if your program allows you could use a dict or list anyway

# A dict example
# Note: I'm using var1 and var2 here for continuity only. 
# Give a more descriptive key if you want
greetings = {
  "var1": "hello",
  "var2": "greetings",
}
selected_greeting = greetings[f"var{choice}"]

# A list example
greetings = ["hello", "greetings"]
selected_greeting = greetings[int(choice) - 1] # Cast to int, input gives us strings. Also subtract 1 because lists are zero indexed
JJ Hassan
  • 395
  • 3
  • 11