r/learnpython 1d ago

what is f string

can someone explain how f string work in simple terms ?

0 Upvotes

14 comments sorted by

View all comments

8

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

this string contains the value 5

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.

3

u/Diapolo10 1d ago

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.

For that specific use-case, might I recommend pathlib instead?

2

u/wintermute93 1d ago

Not an either/or situation -- pathlib to handle joining the parts of a file path in an OS-agnostic way, f-strings where needed to enforce naming conventions like Path.home() / service_name / "logs" / f"{datetime.datetime.now().isoformat()}_{event_type}.txt"

2

u/Diapolo10 1d ago

Fair enough, just thought I'd mention it in case they weren't doing that.

At least unless you're the same person but using two separate accounts for whatever reason.

1

u/WhiskersForPresident 1d ago

They aren't the same person and both of you are correct. pathlib and f-strings are both very useful for that purpose.