What is meant by 2f in Python?

The placeholder is defined using curly brackets: {}. Read more about the placeholders in the Placeholder section below.

The format() method returns the formatted string.


Syntax

string.format(value1, value2...)

Parameter Values

ParameterDescriptionvalue1, value2...Required. One or more values that should be formatted and inserted in the string.

The values are either a list of values separated by commas, a key=value list, or a combination of both.

The values can be of any data type.


The Placeholders

The placeholders can be identified using named indexes {price}, numbered indexes {0}, or even empty placeholders {}.

Python v2.7 introduced a new string fomatting method, that is now the default in Python3. I started this string formatting cookbook as a quick reference to help me format numbers and strings. Thanks to other contributors I've expanded the examples over time.

Python 3.6 introduced, formatted string literals, often referred to as f-strings as another method to help format strings. below.

Number Formatting

The following table shows various ways to format numbers using Python's str.format(), including examples for both float formatting and integer formatting.

To run examples use:

pi = 3.1415926
precision = 4
print( "{:.{}f}".format( pi, precision ) )
~~ 3.1415
2

To get the output of the first example, formatting a float to two decimal places, you would run:

pi = 3.1415926
precision = 4
print( "{:.{}f}".format( pi, precision ) )
~~ 3.1415
3

NumberFormatOutputDescription3.1415926{:.2f}3.14Format float 2 decimal places3.1415926{:+.2f}+3.14Format float 2 decimal places with sign-1{:+.2f}-1.00Format float 2 decimal places with sign2.71828{:.0f}3Format float with no decimal places5{:0>2d}05Pad number with zeros (left padding, width 2)5{:x<4d}5xxxPad number with x's (right padding, width 4)10{:x<4d}10xxPad number with x's (right padding, width 4)1000000{:,}1,000,000Number format with comma separator0.25{:.2%}25.00%Format percentage1000000000{:.2e}1.00e+09Exponent notation13{:10d}        13Right aligned (default, width 10)13{:<10d}13Left aligned (width 10)13{:^10d}    13Center aligned (width 10)

string.format() basics

Here are a couple of examples of basic string substitution, the

pi = 3.1415926
precision = 4
print( "{:.{}f}".format( pi, precision ) )
~~ 3.1415
4 is the placeholder for substituted variables. If no format is specified, it will insert and format as a string.

s1 = "show me the {}".format("money")
s2 = "hmmm, this is a {} {}".format("tasty", "burger")

You can also use the numeric position of the variables and change them in the strings, this gives some flexibility when doing the formatting, if you make a mistake in the order you can easily correct without shuffling all the variables around.

s1 = " {0} is better than {1} ".format("emacs", "vim")
s2 = " {1} is better than {0} ".format("emacs", "vim")

đź’ˇ Tip: You can use

pi = 3.1415926
precision = 4
print( "{:.{}f}".format( pi, precision ) )
~~ 3.1415
4 as a variable inside the formatting brackets (h/t Peter Beens for tip). This example uses a precision variable to control how many decimal places to show:

pi = 3.1415926
precision = 4
print( "{:.{}f}".format( pi, precision ) )
~~ 3.1415

Older % string formatter

Prior to python 2.6, the way to format strings tended to be a bit simpler, though limited by the number of arguments it can receive. These methods still work as of Python 3.3, but there are veiled threats of deprecating them completely though no time table. [PEP-3101]

Formatting a floating point number:

An example comparing the older

pi = 3.1415926
precision = 4
print( "{:.{}f}".format( pi, precision ) )
~~ 3.1415
6 with
pi = 3.1415926
precision = 4
print( "{:.{}f}".format( pi, precision ) )
~~ 3.1415
7 for formatting a float number:

pi = 3.14159
print(" pi = %1.2f " % pi)         # old
print(" pi = {:.2f}".format( pi )) # new

Multiple Substitution Values

An example comparing variable substitution:

s1 = "cats"
s2 = "dogs"
s3 = " %s and %s living together" % (s1, s2)
s4 = " {} and {} living together ".format(s1, s2)

Not Enough Arguments

Using the older format method, I would often get the errors:

TypeError: not enough arguments for format string

or

TypeError: not all arguments converted during string formatting

because I miscounted my substitution variables, doing something like the following made it easy to miss a variable.

The new Python string formatter you can use numbered parameters so you don't have to count how many you have, at least on half of it.

set = " ({0}, {1}, {2}, {3}, {4}, {5}, {6}, {7}) ".format(a,b,c,d,e,f,g)

More String Formatting with .format()

The format() function offers a fair amount of additional features and capabilities, here are a few useful tips and tricks using .format()

Named Arguments

You can use the string format as a template engine using named arguments, instead of requiring a strict order.

madlib = " The {object} is against the {place}".format(object="chair", place="wall")
~~ The chair is against the wall

đź’ˇ If you are using Python 3.6 or greater, see the below for an easier way to create template--they also compute faster interpolations!

Reuse Same Variable Multiple Times

Using % to format requires a strict ordering of variables, the

pi = 3.1415926
precision = 4
print( "{:.{}f}".format( pi, precision ) )
~~ 3.1415
8 method allows you to put them in any order as well as repeating for reuse.

str = "Oh {0}, {0}! wherefore art thou {0}?".format("Romeo")
~~ Oh Romeo, Romeo! wherefore art thou Romeo?

Convert Values to Different Bases

A surprising use, you can use the string format command to convert numbers to different bases. Use the letter in the formatter to indicate which number base: decimal, hex, octal, or binary.

This example formats the number

pi = 3.1415926
precision = 4
print( "{:.{}f}".format( pi, precision ) )
~~ 3.1415
9 in each base:

s1 = " {0} is better than {1} ".format("emacs", "vim")
s2 = " {1} is better than {0} ".format("emacs", "vim")
0

Use Format as a Function

You can use

pi = 3.14159
print(" pi = %1.2f " % pi)         # old
print(" pi = {:.2f}".format( pi )) # new
0 as a function to separate text and formatting from code. For example, at the beginning of your program include all your formats for later use.

s1 = " {0} is better than {1} ".format("emacs", "vim")
s2 = " {1} is better than {0} ".format("emacs", "vim")
1

Hat tip to earthboundkids who provided this on reddit.

Using format as a function can be used to adjust formating by user preference.

s1 = " {0} is better than {1} ".format("emacs", "vim")
s2 = " {1} is better than {0} ".format("emacs", "vim")
2

Internationalization

To use locale specific formatting for numbers, you need to first set the locale, and then use the formating code

pi = 3.14159
print(" pi = %1.2f " % pi)         # old
print(" pi = {:.2f}".format( pi )) # new
1 instead of
pi = 3.14159
print(" pi = %1.2f " % pi)         # old
print(" pi = {:.2f}".format( pi )) # new
2. For example, using commas or periods to separate thousands in numbers based on the user's locale.

Here is an example, setting locale and formatting a number to display the proper separator:

s1 = " {0} is better than {1} ".format("emacs", "vim")
s2 = " {1} is better than {0} ".format("emacs", "vim")
3

Escaping Braces

If you need to use braces when using

pi = 3.14159
print(" pi = %1.2f " % pi)         # old
print(" pi = {:.2f}".format( pi )) # new
3 just double them up:

s1 = " {0} is better than {1} ".format("emacs", "vim")
s2 = " {1} is better than {0} ".format("emacs", "vim")
4

Table Formatting Data

Use the width and the left and right justification to align your data into a nice table format. Here's an example to show how to format:

s1 = " {0} is better than {1} ".format("emacs", "vim")
s2 = " {1} is better than {0} ".format("emacs", "vim")
5

This would output:

s1 = " {0} is better than {1} ".format("emacs", "vim")
s2 = " {1} is better than {0} ".format("emacs", "vim")
6

F-Strings

Python 3.6 introduced formatted string literals--yet another method of formatting strings--referred to as f-strings because you start the string specifying an

pi = 3.14159
print(" pi = %1.2f " % pi)         # old
print(" pi = {:.2f}".format( pi )) # new
4 on the outside of the quotes, like so
pi = 3.14159
print(" pi = %1.2f " % pi)         # old
print(" pi = {:.2f}".format( pi )) # new
5. F strings use a shorter syntax making it easier and more template-like.

s1 = " {0} is better than {1} ".format("emacs", "vim")
s2 = " {1} is better than {0} ".format("emacs", "vim")
7

Formatted string literals support running functions inside of the brackets

pi = 3.14159
print(" pi = %1.2f " % pi)         # old
print(" pi = {:.2f}".format( pi )) # new
6 this allows you to:

1. Do math with f-strings:

s1 = " {0} is better than {1} ".format("emacs", "vim")
s2 = " {1} is better than {0} ".format("emacs", "vim")
8

2. Call functions with f-strings;

s1 = " {0} is better than {1} ".format("emacs", "vim")
s2 = " {1} is better than {0} ".format("emacs", "vim")
9

You can use f-strings using the three different type of quotation marks in Python, single, double, or triple quotes. The following will all output the same:

pi = 3.1415926
precision = 4
print( "{:.{}f}".format( pi, precision ) )
~~ 3.1415
0

The one thing you'll want to be careful is mixing the two formats, if you try to use

pi = 3.1415926
precision = 4
print( "{:.{}f}".format( pi, precision ) )
~~ 3.1415
4 inside of an f-string, you will get the error:

What does %2f mean?

“print” treats the % as a special character you need to add, so it can know, that when you type “f”, the number (result) that will be printed will be a floating point type, and the “. 2” tells your “print” to print only the first 2 digits after the point.

How do you use %2f in Python?

2f is a placeholder for floating point number. So %d is replaced by the first value of the tuple i.e 12 and %. 2f is replaced by second value i.e 150.87612 . ... Python String Formatting..

Is 2f a float?

2f syntax tells Java to return your variable (value) with 2 decimal places (. 2) in decimal representation of a floating-point number (f) from the start of the format specifier (%).

Why is 2f not working in Python?

2f format, the value should be a float , not a string, so you need to convert the input to float ( input() returns a string, there's no need to use str() on the result. And you can't concatenate $ to the value before formatting it, you need to concatenate that to the result.