+ 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.)
7 Antworten
+ 8
Here are a couple ways:
String concatenation
"Salutations, " + name + "!"
String interpolation as an f-string
f"Salutations, {name}!"
+ 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 .
+ 5
Or
"{name}".format(name=variable)
+ 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.
+ 3
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}")
+ 2
Some examples in this code:
https://sololearn.com/compiler-playground/cBeeHx9sunxb/?ref=app
+ 1
you can use--> print(f"hi, {name}")