Showing results for python print format
Search instead for python3 print format

In Python 3.6 f-strings are introduced.

You can write like this

print (f"So, you're {age} old, {height} tall and {weight} heavy.")

For more information Refer: https://docs.python.org/3/whatsnew/3.6.html

Answer from Nithin R on Stack Overflow
๐ŸŒ
Python documentation
docs.python.org โ€บ 3 โ€บ tutorial โ€บ inputoutput.html
7. Input and output โ€” Python 3.15.0 documentation
Given format % values (where format is a string), % conversion specifications in format are replaced with zero or more elements of values. This operation is commonly known as string interpolation. For example: >>> import math >>> print('The value of pi is approximately %5.3f.'
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-output-formatting
Python - Output Formatting - GeeksforGeeks
The string modulo operator (%) is one of the oldest ways to format strings in Python. It allows you to embed values within a string by placing format specifiers in the string. Each specifier starts with a % and ends with a character that represents the type of value being formatted. ... # string modulo operator(%) print("Geeks : -, Portal : %5.2f" % (1, 05.333)) print("Total students : =, Boys : -" % (240, 120)) # print integer value print("%7.3o" % (25)) # print octal value print(".3E" % (356.08977)) # print exponential value
Published: July 11, 2025
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ python_string_formatting.asp
Python String Formatting
A modifier is included by adding a colon : followed by a legal formatting type, like .2f which means fixed point number with 2 decimals: ... You can perform Python operations inside the placeholders. ... price = 59 tax = 0.25 txt = f"The price is {price + (price * tax)} dollars" print(txt) Try it Yourself ยป
๐ŸŒ
Bentley
cissandbox.bentley.edu โ€บ sandbox โ€บ wp-content โ€บ uploads โ€บ 2022-02-10-Documentation-on-f-strings-Updated.pdf pdf
Updated 2022 A Guide to Formatting with f-strings in Python
other ways for formatting strings, the Zen of Python states that simple is better than complex ยท and practicality beats purity--and f-strings are really the most simple and practical way for ยท formatting strings. They are also faster any of the previous more commonly used string ยท formatting mechanisms. To use formatted string literals, begin a string with f or F before the opening quotation mark or ยท triple quotation mark in a print() statement.
๐ŸŒ
PyFormat
pyformat.info
PyFormat: Using % and .format() for great good!
The new-style simple formatter calls by default the __format__() method of an object for its representation. If you just want to render the output of str(...) or repr(...) you can use the !s or !r conversion flags. In %-style you usually use %s for the string representation but there is %r for a repr(...) conversion. class Data(object): def __str__(self): return 'str' def __repr__(self): return 'repr' ... In Python 3 there exists an additional conversion flag that uses the output of repr(...) but uses ascii(...) instead.
๐ŸŒ
Mooc
programming-25.mooc.fi โ€บ part-4 โ€บ 5-print-statement-formatting
Print statement formatting - Python Programming MOOC 2025
The format specifier .2f states that we want to display 2 decimals. The letter f at the end means that we want the variable to be displayed as a float, i.e. a floating point number. Here's another example, where we specify the amount of whitespace reserved for the variable in the printout.
Find elsewhere
๐ŸŒ
Mimo
mimo.org โ€บ glossary โ€บ python โ€บ formatted-strings
Python Formatted Strings / f-string formatting Guide
from datetime import datetime user_last_login = datetime(2024, 2, 16, 11, 38) print(f"Last login: {user_last_login:%B %d, %Y at %H:%M}") f-strings also support JSON-friendly representations using repr, which ensures that objects are formatted in a readable string form. ... f-strings can include more than variables and values. They can include expressions, function calls, and even conditional logic: ... Python's so-called format mini-language provides advanced control over string formatting.
๐ŸŒ
YouTube
youtube.com โ€บ coding for everybody
Python: Print Formatting - YouTube
Welcome to Python for Everybody, the complete Python course for beginners, intermediate and advanced developers. Course links below! https://pythonforeverybo...
Published: August 4, 2020
Views: 21K
๐ŸŒ
Python Course
python-course.eu โ€บ python-tutorial โ€บ formatted-output.php
22. Formatted Output | Python Tutorial | python-course.eu
Additionally, we can modify the formatting with the sign option, which is only valid for number types: ... Enjoying this page? We offer live Python training courses covering the content of this site. ... Just to mention it once more: We could have used empty curly braces in the previous example! Using keyword parameters: print("The capital of {province} is {capital}".format(province="Ontario",capital="Toronto"))
๐ŸŒ
mkaz.blog
mkaz.blog โ€บ working-with-python โ€บ string-formatting
Python String Formatting: Complete Guide - mkaz.blog
num = 255 print(f"Decimal: {num:d}") # Decimal: 255 print(f"Hexadecimal: {num:x}") # Hexadecimal: ff print(f"Hex (upper): {num:X}") # Hex (upper): FF print(f"Octal: {num:o}") # Octal: 377 print(f"Binary: {num:b}") # Binary: 11111111 # With prefixes for clarity print(f"Hex with prefix: {num:#x}") ...
๐ŸŒ
Mimo
mimo.org โ€บ glossary โ€บ python โ€บ print-function
Explore Python's print() function, master output customization
The pprint (pretty-print) module in Python provides a way to format complex data structures in a readable way.
๐ŸŒ
Mooc
programming-24.mooc.fi โ€บ part-4 โ€บ 5-print-statement-formatting
Print statement formatting - Python Programming MOOC 2024
The format specifier .2f states that we want to display 2 decimals. The letter f at the end means that we want the variable to be displayed as a float, i.e. a floating point number. Here's another example, where we specify the amount of whitespace reserved for the variable in the printout.
๐ŸŒ
Python Reference
python-reference.readthedocs.io โ€บ en โ€บ latest โ€บ docs โ€บ functions โ€บ format.html
format โ€” Python Reference (The Right Way) 0.1 documentation
Binary format. Outputs the number in base 2. ... Character. Converts the integer to the corresponding unicode character before printing.
๐ŸŒ
Real Python
realpython.com โ€บ python-formatted-output
A Guide to Modern Python String Formatting Tools โ€“ Real Python
February 1, 2025 - In modern Python, you have f-strings and the .format() method to approach the tasks of interpolating and formatting strings. These tools help you embed variables and expressions directly into strings, control text alignment, and use custom format specifiers to modify how values appear.
Top answer
1 of 7
151

The f means Formatted string literals and it's new in Python 3.6.


A formatted string literal or f-string is a string literal that is prefixed with f or F. These strings may contain replacement fields, which are expressions delimited by curly braces {}. While other string literals always have a constant value, formatted strings are really expressions evaluated at run time.


Some examples of formatted string literals:

>>> name = "Fred"
>>> f"He said his name is {name}."
"He said his name is Fred."

>>> name = "Fred"
>>> f"He said his name is {name!r}."
"He said his name is Fred."

>>> f"He said his name is {repr(name)}." # repr() is equivalent to !r
"He said his name is Fred."

>>> width = 10
>>> precision = 4
>>> value = decimal.Decimal("12.34567")
>>> f"result: {value:{width}.{precision}}" # nested fields
result: 12.35

>>> today = datetime(year=2023, month=1, day=27)
>>> f"{today:%B %d, %Y}" # using date format specifier
January 27, 2023

>>> number = 1024
>>> f"{number:#0x}" # using integer format specifier
0x400
2 of 7
63

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

Example:

agent_name = 'James Bond'
kill_count = 9


# old ways
print("%s has killed %d enemies" % (agent_name,kill_count))

print('{} has killed {} enemies'.format(agent_name,kill_count))
print('{name} has killed {kill} enemies'.format(name=agent_name,kill=kill_count))
    

# f-strings way
print(f'{agent_name} has killed {kill_count} enemies')

The f or F in front of strings tell Python to look at the values , expressions or instance inside {} and substitute them with the variables values or results if exists. The best thing about f-formatting is that you can do cool stuff in {}, e.g. {kill_count * 100}.

You can use it to debug using print e.g.

print(f'the {agent_name=}.')
# the agent_name='James Bond'

Formatting, such as zero-padding, float and percentage rounding is made easier:

print(f'{agent_name} shoot with {9/11 : .2f} or {9/11: .1%} accuracy')
# James Bond shoot with  0.82 or  81.8% accuracy 

Even cooler is the ability to nest and format. Example date


from datetime import datetime

lookup = {
    '1': 'st',
    '21': 'st',
    '31': 'st',
    '2': 'nd',
    '22': 'nd',
    '3': 'rd',
    '23': 'rd'
}

dato = datetime.now()

print(f"{dato: %B %-d{lookup.get(f'{dato:%-d}', 'th')} %Y}")

# April 23rd 2022

Pretty formatting is also easier

tax = 1234

print(f'{tax:,}') # separate 1k \w comma
# 1,234

print(f'{tax:,.2f}') # all two decimals 
# 1,234.00

print(f'{tax:~>8}') # pad left with ~ to fill eight characters or < other direction
# ~~~~1234

print(f'{tax:~^20}') # centre and pad
# ~~~~~~~~1234~~~~~~~~

The __format__ allows you to funk with this feature. Example


class Money:
    
    def __init__(self, value, currency='โ‚ฌ'):
        self.currency = currency
        self.value = value
        
    def __repr__(self):
        return f'Money(value={self.value}, currency={self.currency})'
        
    def __format__(self, *_):
        
        return f"{self.currency}{float(self.value):.2f}"
        
        
tax = 12.3446
money = Money(tax, currency='$')

print(f'{money}')
# $12.34

print(money)
# Money(value=12.3446, currency=$)

There is much more. Readings:

  • PEP 498 Literal String Interpolation
  • Python String Formatting
๐ŸŒ
Yurok Language Project
linguistics.berkeley.edu โ€บ plab โ€บ guestwiki โ€บ index.php
Output formatting in Python - Phonlab
October 15, 2013 - We use the format string by calling the format() method on fmt and supplying values for the keyword fields we defined in fmt. The >> indicates that the print line is executed in a Python interpreter, and the second line is the interpreter output.
๐ŸŒ
Learn Python
learnpython.org โ€บ en โ€บ String_Formatting
String Formatting - Learn Python - Free Interactive Python Tutorial
Python uses C-style string formatting to create new, formatted strings. The "%" operator is used to format a set of variables enclosed in a "tuple" (a fixed size list), together with a format string, which contains normal text together with "argument specifiers", special symbols like "%s" and "%d". Let's say you have a variable called "name" with your user name in it, and you would then like to print(out a greeting to that user.)
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ ref_string_format.asp
Python String format() Method
Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Practice Problems Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Training ... The format() method formats the specified value(s) and insert them inside the string's placeholder.
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ python_strings_format.asp
Python - Format Strings
Python Examples Python Compiler ... Interview Q&A Python Training ... age = 36 #This will produce an error: txt = "My name is John, I am " + age print(txt) Try it Yourself ยป ยท But we can combine strings and numbers by using f-strings or the format() method!...