How to use ‘variables’ in a ‘python’ string | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How to use ‘variables’ in a ‘python’ string

I was just messing around with the little knowledge of python I possess. For whatever reason I can’t remember how to use the NAME of my variable in a string instead of just putting VALUE. (Trying to make a discord bot that will greet whoever joins my discord.)

4th May 2024, 9:11 PM
Maleet Yobal
7 Answers
+ 8
Here are a couple ways: String concatenation "Salutations, " + name + "!" String interpolation as an f-string f"Salutations, {name}!"
4th May 2024, 11:24 PM
Brian
Brian - avatar
+ 7
Maleet Yobal , we can put also things together when doing an output with the print() function. > assuming we have a variable which is named `age` with an input value of 42, we can do: print('you are', age, 'years old!') > here a sample using 2 int variables `num1` and `num2` with the values of 2 and 7: print('the sum of', num1, '+', num2, '=', num1 + num2) >> however, the preferred way should be to use f-strings as already mentioned by Brian .
5th May 2024, 5:40 AM
Lothar
Lothar - avatar
+ 5
Or "{name}".format(name=variable)
5th May 2024, 1:16 PM
Toni Isotalo
Toni Isotalo - avatar
+ 4
... and just another variant print(f" hello {name}") the curly brackets will be replaced by the value of the variable name. This miracle occurs because of the f before the string.
5th May 2024, 9:49 AM
Oma Falk
Oma Falk - avatar
+ 2
To use the name of a variable in a string without putting its value, you can use f-strings in Python. Code: variable_name = "my_variable" print(f"The name of the variable is: {variable_name}")
6th May 2024, 3:54 PM
Palla Sri Karthikeya Narayana Raju
6th May 2024, 7:48 PM
Allan Prommik
Allan Prommik - avatar
+ 1
you can use--> print(f"hi, {name}")
6th May 2024, 5:31 PM
alfinnn
alfinnn - avatar