Skip to content

Print(f Python) | Python f print – Example code

  • by

What is print(f”…”)

Print(f Python): The f means Formatted string literals and it’s new in Python 3.6.

The f-string was introduced(PEP 498). In short, it is a way to format your string that is more readable and fast.

Example:

The f or F in front of strings tells Python to look at the values inside {} and substitute them with the values of the variables if exist.

agent = 'James Bond'
num = 9

# old ways
print('{0} has {1} number '.format(agent, num))

# f-strings way
print(f'{agent} has {num} number')

Output:

What is print f python

More detail about Python f print

The variables in the curly { } braces are displayed in the output as a normal print statement. f is either lower or upper it’ll work the same.

Print F-strings are faster than the two most commonly used string old formatting methods, which are % formatting and str.format(). 

import datetime

today = datetime.datetime.today()
print(f"{today:%B %d, %Y}")

Output: September 09, 2021

What does ‘f’ means before a string in Python?

These are called f-strings and are quite straightforward: when using an “f” in front of a string, all the variables inside curly brackets are read and replaced by their value. For example:

age = 18
message = f"You are {age} years old"
print(message)

Output: You are 18 years old

How to escape curly brackets { } in f-strings?

Although there is a custom syntax error from the parser, the same trick works as for calling .format on regular strings.

Use double curlies:

foo = 'test'

print(f'{foo} {{bar}}')

Output: test {bar}

Do comment if you have any doubts or suggestions on this Python topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading