+ 10
How to Format a string in python useing f-string ?
I am getting error in sololearn app as well as in my pycharm in pc .so what is the correct way to format a string useing f-String
6 odpowiedzi
+ 5
name = "Russ"
print(f"Hello {name}, how are you?")
With f-strings, you put the name of your variable in curly brackets and it will appear in your string.
+ 8
A small addition to Russ post: Inside the curly brackets functions can be used:
f"{name.upper()}“
or calculations can be done:
f"price - {(price * 0.93):.2f}"
+ 6
It would be very helpful if you could share the code that causes your trouble. So we can help you more purposefully.
+ 4
@Russ what are fstrings really used for?
+ 4
Vusumuzi Mabena they are used so that you can easily insert variables into a printed string.
If you had something like
name = "Russ"
age = 36
lucky_number = 4
to print a sentence like "Hello Russ, you are 36 years old and your lucky number is 4!", without f-strings you would need this
print("Hello", name + ", you are", age, "years old and your lucky number is", str(lucky_number) + "!")
Lots of commas and plus signs and the need to convert a number to a string and use + if you don't want to have a space after it. With f-strings it is much easier...
print(f"Hello {name}, you are {age} years old and your lucky number is {lucky_number}!")