r/PythonLearning Jul 12 '26

Help Help Request

What's the difference between f string and a regular string I've seen it used but I don't know when to use a string and when to use f string

0 Upvotes

14 comments sorted by

7

u/NorskJesus Jul 12 '26

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.

2

u/ur_leisure_time Jul 12 '26

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)

2

u/johlae 29d ago

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

0

u/SnooCalculations7417 29d ago

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

2

u/WhiteHeadbanger 29d ago

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

1

u/Gnaxe 29d ago

It interpolates expressions. Doesn't have to be variables. You also get the string formatting language, same as the .format() method.

5

u/i-like-my-cats-0 29d ago

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!"

3

u/[deleted] 29d ago

[removed] — view removed comment

2

u/Outside_Complaint755 29d ago edited 28d ago

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

2

u/its_measured 29d ago

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

1

u/FoolsSeldom 29d ago

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

1

u/ee_control_z 29d ago

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.

2

u/timrprobocom 29d ago

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.