How to Format a string in python useing f-string ? | Sololearn: Learn to code for FREE!
Neuer Kurs! Jeder Programmierer sollte generative KI lernen!
Kostenlose Lektion ausprobieren
+ 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

5th Jun 2019, 4:12 PM
Vijay(v-star🌟)
Vijay(v-star🌟) - avatar
6 Antworten
+ 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.
5th Jun 2019, 4:16 PM
Russ
Russ - avatar
+ 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}"
27th Jun 2019, 5:33 PM
Lothar
Lothar - avatar
+ 6
It would be very helpful if you could share the code that causes your trouble. So we can help you more purposefully.
5th Jun 2019, 5:24 PM
Lothar
Lothar - avatar
+ 4
@Russ what are fstrings really used for?
27th Jun 2019, 12:47 PM
Vusumuzi Mabena
Vusumuzi Mabena - avatar
+ 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}!")
27th Jun 2019, 3:06 PM
Russ
Russ - avatar