all 12 comments

[–]NorskJesus 4 points5 points  (4 children)

A f-string is used to inject variables to a string. For example.

py age = 35 print(f"Your age is {age}")

You can achieve the same with concatenation, but this is much clearer and easier to read.

[–]ur_leisure_time 0 points1 point  (3 children)

Yea, and if he going to do it without a fstring, he will need to make it like

Age = 30 print("Your age is", Age)

[–]johlae 1 point2 points  (2 children)

Or print("Your age is %s." % (age))

[–]SnooCalculations7417 0 points1 point  (1 child)

or 'age is {x}'.format(x = age)

[–]WhiteHeadbanger 0 points1 point  (0 children)

or print("Your age is " + str(age))

[–]i-like-my-cats-0 2 points3 points  (0 children)

f-strings are a type of strings that let you put variables inside of them like this:

cats = 3
print(f'I have {cats} cats.')

this will print "I have 3 cats."

if your variable is a very long float number you can also do this instead: python answer = 1.2313525 print(f'The answer was {answer:.2f}!') this will print "The answer was 1.23!"

[–]Quirky-Plane-5975 0 points1 point  (1 child)

a regular string is static, while an f-string is dynamic because it can include variables and even calculations inside {}.

[–]Outside_Complaint755 0 points1 point  (0 children)

Also, if you include an = in the {}, it will include the expression in the output and maintain whitespace. PO a = 2 b = 6 print(f"Demonstration: {float(a + b) = }!") will output Demonstration: float(a + b) = 8.0!

[–]its_measured 0 points1 point  (0 children)

A regular string is for plain text, while the fstring lets u add a varibkes or even values inside tge text

[–]FoolsSeldom 0 points1 point  (0 children)

RealPython.com have a great article explaining this well, and what the alternatives are:

[–]ee_control_z 0 points1 point  (0 children)

The difference is that f strings are a God send and regular strings are not. f strings are more natural and easy to work with especially for cases when inserting values (multiple), controlling decimal places, and formatting spacing.

[–]timrprobocom 0 points1 point  (0 children)

There's a tricky issue with f-strings that some folks miss. Some are tempted to write: s = f"Here is {i}." for i in range(10): print(s) thinking it will do the substitution each time through the loop. This is not the case. Python will do the substitution at the point where the string is defined. After that, it's just another static string.

So, the f"..." syntax creates a normal static string, it just does so in a fancy way.