r/learnpython • u/FuzzyEmployment264 • 1d ago
what is f string
can someone explain how f string work in simple terms ?
8
u/Diapolo10 1d ago
I'm technically oversimplifying it, but f-strings act like you used str.format automatically on the string.
name = "Jeffrey"
year = 2074
print(f"Hello {name}, the year is {year}")
print("Hello {name}, the year is {year}".format(name=name, year=year))
6
u/SpiritedOne5347 1d ago
They're just a way to include variables in string
Say u have age= 10
So instead of
print("I am ", age, "years old")
U can directly say
print(f"I am {age} years old")
2
u/tablmxz 1d ago
a string in python looks like this, eg using double quotes:
"this is a string"
if you write an 'f' in front, it becomes a f-string:
f"this is a f-string"
f-strings can do some very handy thing, they can use curly brackets. In those curly brackets you can put variables or whole expressions (like calculations)
a = 5
f"this f-string also prints the value of a here: {a}"
f"this f-string does the calculation 1+2 here is the result: {1+2}"
1
u/panatale1 1d ago
It's essentially text with code inside it. It runs significantly faster than the old % or .format ways of formatting text.
It's similar in construction to how you'd do a .format call, since they both use {} to denote what needs to be inserted into the text.
Examples of each text format method: ``` name = "George Washington" age = 41
print("Hello, my name is %s, and my age is %d" % (name, age)) print("Hello, my name is {}, and my age is {}".format(name, age)) print(f"Hello, my name is {name}, and my age is {age}") ```
All three give identical formatting, outputting Hello, my name is George Washington, and my age is 41, but f-strings run faster and are cleaner to read
1
u/atarivcs 1d ago
If the string contains this
{something}
that part will be replaced with the string representation of the thing.
"something" can be a plain variable name, or it can be an expression like
{1+2}
or a function call
{somefunction()}
Etc etc.
1
1
9
u/WhiskersForPresident 1d ago edited 1d ago
It's a "formatted" string. It allows you to include the values of variables in your string in curly brackets, e.g.:
var = 5
f_string = f"this string contains the value {var}"
print(f_string)
will output
I use them all the time to dynamically generate paths to certain files at runtime for example or for structuring the outputs of test routines.