You are on page 1of 15

3/20/2018 Python String format()

TUTORIAL EXAMPLES BUILT-IN FUNCTIONS 

Python String format()


The string format() method formats the given string into a nicer output in Python.

The syntax of format() method is:

template.format(p0, p1, ..., k0=v0, k1=v1, ...)

Here, p0, p1,... are positional arguments and, k0, k1,... are keyword arguments with
values v0, v1,... respectively.

And, template is a mixture of format codes with placeholders for the arguments.

String format() Parameters


format() method takes any number of parameters. But, is divided into two types of
parameters:

Positional parameters - list of parameters that can be accessed with index of


parameter inside curly braces {index}
Keyword parameters - list of parameters of type key=value, that can be accessed
with key of parameter inside curly braces {key}

Return value from String format()


The format() method returns the formatted string.

How String format() works?


https://www.programiz.com/python-programming/methods/string/format 1/15
3/20/2018 Python String format()

The format() reads the type of arguments passed to it and formats it according to the
TUTORIAL EXAMPLES BUILT-IN FUNCTIONS
format codes de ned in the string. 

For positional arguments

Here, Argument 0 is a string "Adam" and Argument 1 is a oating number 230.2346.

Note:  Argument list starts from 0 in Python.

The string "Hello {0}, your balance is {1:9.3f}" is the template string. This contains the
format codes for formatting.

The curly braces are just placeholders for the arguments to be placed. In the above
example, {0} is placeholder for "Adam" and {1:9.3f} is placeholder for 230.2346 .

Since the template string references format() arguments as {0} and {1}, the arguments are
positional arguments. They both can also be referenced without the numbers as {} and
Python internally converts them to numbers.

Internally,

Since "Adam" is the 0th argument, it is placed in place of {0}. Since, {0} doesn't
contain any other format codes, it doesn't perform any other operations.
However, it is not the case for 1st argument 230.2346 . Here, {1:9.3f} places
230.2346 in its place and performs the operation 9.3f.
f speci es the format is dealing with a oat number. If not correctly speci ed, it will
give out an error.
The part before the "." (9) speci es the minimum width/padding the number
(230.2346) can take. In this case, 230.2346 is allotted a minimum of 9 places including
the ".".
If no alignment option is speci ed, it is aligned to the right of the remaining spaces.
(For strings, it is aligned to the left.)
The part after the "." (3) truncates the decimal part (2346) upto the given number. In
this case, 2346 is truncated after 3 places.
Remaining numbers (46) is rounded o outputting 235.

https://www.programiz.com/python-programming/methods/string/format 2/15
3/20/2018 Python String format()

TUTORIAL
For EXAMPLES
keyword BUILT-IN FUNCTIONS
arguments 

We've used the same example from above to show the di erence between keyword and
positional arguments.

Here, instead of just the parameters, we've used a key-value for the parameters. Namely,
name="Adam" and blc=230.2346 .

Since, these parameters are referenced by their keys as {name} and {blc:9.3f} , they are
known as keyword or named arguments.

Internally,

The placeholder {name} is replaced by the value of name - "Adam". Since, it doesn't
contain any other format codes, "Adam" is placed.
For the argument blc=230.2346, the placeholder {blc:9.3f} is replaced by the value
230.2346. But before replacing it, like previous example, it performs 9.3f operation on
it.
This outputs   230.235. The decimal part is truncated after 3 places and remaining
digits are rounded o . Likewise, the total width is assigned 9 leaving two spaces to
the left.

Basic formatting with format()


The format() method allows the use of simple placeholders for formatting.

Example 1: Basic formatting for default, positional and


keyword arguments
script.py IPython Shell
1 # default arguments
2 print("Hello {}, your balance is {}.".format("Adam", 230.2346))
3
4 # positional arguments
5 print("Hello {0}, your balance is {1}.".format("Adam", 230.2346))

https://www.programiz.com/python-programming/methods/string/format 3/15
3/20/2018 Python String format()
6
# keyword arguments
7
TUTORIAL
8
EXAMPLES
print("Hello {name}, yourBUILT-IN FUNCTIONS
balance is {blc}.".format(name="Adam", blc=230.2346)) 
9
# mixed arguments
10
print("Hello {0}, your balance is {blc}.".format("Adam", blc=230.2346))
11

Run 

Powered by DataCamp

When you run the program, the output will be same for all:

Hello Adam, your balance is 230.2346.


Hello Adam, your balance is 230.2346.
Hello Adam, your balance is 230.2346.
Hello Adam, your balance is 230.2346.

Note: In case of mixed arguments, keyword arguments has to always follow positional
arguments.

Numbers formatting with format()


You can format numbers using the format speci er given below:

Number Formatting Types

Type Meaning

d Decimal integer

c Corresponding Unicode character

b Binary format

o Octal format

x Hexadecimal format (lower case)

X Hexadecimal format (upper case)

n Same as 'd'. Except it uses current locale setting for number separator

e Exponential notation. (lowercase e)

https://www.programiz.com/python-programming/methods/string/format 4/15
3/20/2018 Python String format()

Type Meaning
TUTORIAL EXAMPLES BUILT-IN FUNCTIONS 
E Exponential notation (uppercase E)

f Displays xed point number (Default: 6)

F Same as 'f'. Except displays 'inf' as 'INF' and 'nan' as 'NAN'

g General format. Rounds number to p signi cant digits. (Default precision: 6)

G Same as 'g'. Except switches to 'E' if the number is large.

% Percentage. Multiples by 100 and puts % at the end.

Example 2: Simple number formatting


script.py IPython Shell
1 # integer arguments
2 print("The number is:{:d}".format(123))
3
4 # float arguments
5 print("The float number is:{:f}".format(123.4567898))
6
7 # octal, binary and hexadecimal format
8 print("bin: {0:b}, oct: {0:o}, hex: {0:x}".format(12))

Run 

Powered by DataCamp

When you run this program, the output will be:

The number is: 123


The number is:123.456790
bin: 1100, oct: 14, hex: c

Example 3: Number formatting with padding for int and


oats
script.py IPython Shell
1 # integer numbers with minimum width
2 print("{:5d}".format(12))
3
4 # width doesn't work for numbers longer than padding
https://www.programiz.com/python-programming/methods/string/format 5/15
3/20/2018 Python String format()
5 print("{:2d}".format(1234))
6
TUTORIAL
7
EXAMPLES BUILT-IN FUNCTIONS
# padding for float numbers 
8 print("{:8.3f}".format(12.2346))
9
10 # integer numbers with minimum width filled with zeros
11 print("{:05d}".format(12))
12
13 # padding for float numbers filled with zeros
14 print("{:08.3f}".format(12.2346))

Run 

Powered by DataCamp

When you run this program, the output will be:

1 2
1 2 3 4
1 2 . 2 3 5
0 0 0 1 2
0 0 1 2 . 2 3 5

Here,

in the rst statement, {:5d} takes an integer argument and assigns a minimum
width of 5. Since, no alignment is speci ed, it is aligned to the right.
In the second statement, you can see the width (2) is less than the number (1234), so
it doesn't take any space to the left but also doesn't truncate the number.
Unlike integers, oats has both integer and decimal parts. And, the mininum width
de ned to the number is for both parts as a whole including ".".
In the third statement, {:8.3f} truncates the decimal part into 3 places rounding o
the last 2 digits. And, the number, now 12.235, takes a width of 8 as a whole leaving
2 places to the left.
If you want to ll the remaining places with zero, placing a zero before the format
speci er does this. It works both for integers and oats: {:05d} and {:08.3f} .

Example 4: Number formatting for signed numbers


script.py IPython Shell
1 # show the + sign
2 print("{:+f} {:+f}".format(12.23, -12.23))
3
4 # show the - sign only
5 print("{:-f} {:-f}".format(12.23, -12.23))
6
7 # show space for + sign
8 print("{: f} {: f}".format(12.23, -12.23))

https://www.programiz.com/python-programming/methods/string/format 6/15
3/20/2018 Python String format()

TUTORIAL EXAMPLES BUILT-IN FUNCTIONS 


Run 

Powered by DataCamp

When you run this program, the output will be:

+12.230000 -12.230000
12.230000 -12.230000
1 2 . 2 3 0 0 0 0 - 1 2 . 2 3 0 0 0 0

Number formatting with alignment

The operators < , ^ , > and = are used for alignment when assigned a certain width to
the numbers.

Number formatting with alignment

Type Meaning

< Left aligned to the remaining space

^ Center aligned to the remaining space

> Right aligned to the remaining space

= Forces the signed (+) (-) to the leftmost position

Example 5: Number formatting with left, right and center


alignment
script.py IPython Shell
1 # integer numbers with right alignment
2 print("{:5d}".format(12))
3
4 # float numbers with center alignment
5 print("{:^10.3f}".format(12.2346))
6
7 # integer left alignment filled with zeros
8 print("{:<05d}".format(12))
9
10 # float numbers with center alignment
11 print("{:=8.3f}".format(-12.2346))

https://www.programiz.com/python-programming/methods/string/format 7/15
3/20/2018 Python String format()

TUTORIAL
Run 
EXAMPLES BUILT-IN FUNCTIONS 

Powered by DataCamp

When you run this program, the output will be:

1 2
1 2 . 2 3 5
1 2 0 0 0
- 1 2 . 2 3 5

Note: Left alignment lled with zeros for integer numbers can cause problems as the 3rd
example which returns 12000, rather than 12.

String formatting with format()


As numbers, string can be formatted in a similar way with format().

Example 6: String formatting with padding and alignment


script.py IPython Shell
1 # string padding with left alignment
2 print("{:5}".format("cat"))
3
4 # string padding with right alignment
5 print("{:>5}".format("cat"))
6
7 # string padding with center alignment
8 print("{:^5}".format("cat"))
9
10 # string padding with center alignment
11 # and '*' padding character
12 print("{:*^5}".format("cat"))

Run 

Powered by DataCamp

When you run this program, the output will be:

c a t
c a t
c a t
* c a t *

https://www.programiz.com/python-programming/methods/string/format 8/15
3/20/2018 Python String format()

Example 7: Truncating strings with format()


TUTORIAL EXAMPLES BUILT-IN FUNCTIONS 
script.py IPython Shell
1 # truncating strings to 3 letters
2 print("{:.3}".format("caterpillar"))
3
4 # truncating strings to 3 letters
5 # and padding
6 print("{:5.3}".format("caterpillar"))
7
8 # truncating strings to 3 letters,
9 # padding and center alignment
10 print("{:^5.3}".format("caterpillar"))
11

Run 

Powered by DataCamp

When you run this program, the output will be:

c a t
c a t
c a t

Formatting class and dictionary members using


format()
Python internally uses getattr() for class members in the form ".age". And, it uses
__getitem__() lookup for dictionary members in the form "[index]".

Example 8: Formatting class members using format()


script.py IPython Shell
1 # define Person class
2 class Person:
3 age = 23
4 name = "Adam"
5
6 # format age
7 print("{p.name}'s age is: {p.age}".format(p=Person()))

Run 
https://www.programiz.com/python-programming/methods/string/format 9/15
3/20/2018 Python String format()

Powered by DataCamp
TUTORIAL EXAMPLES BUILT-IN FUNCTIONS 
When you run this program, the output will be:

Adam's age is: 23

Here, Person object is passed as a keyword argument p .

Inside the template string, Person's name and age are accessed using .name and .age
respectively.

Example 9: Formatting dictionary members using format()


script.py IPython Shell
1 # define Person dictionary
2 person = {'age': 23, 'name': 'Adam'}
3
4 # format age
5 print("{p[name]}'s age is: {p[age]}".format(p=person))

Run 

Powered by DataCamp

When you run this program, the output will be:

Adam's age is: 23

Similar to class, person dictionary is passed as a keyword argument p .

Inside the template string, person's name and age are accessed using [name] and [age]
respectively.

There's an easier way to format dictionaries in Python using str.format(**mapping) .

script.py IPython Shell


1 # define Person dictionary
2 person = {'age': 23, 'name': 'Adam'}
3

https://www.programiz.com/python-programming/methods/string/format 10/15
3/20/2018 Python String format()
4 # format age
5 print("{name}'s
TUTORIAL age is: {age}".format(**person))
EXAMPLES BUILT-IN FUNCTIONS 

Run 

Powered by DataCamp

** is a format parameter (minimum eld width).

Arguments as format codes using format()


You can also pass format codes like precision, alignment, ll character as positional or
keyword arguments dynamically.

Example 10: Dynamic formatting using format()


script.py IPython Shell
1 # dynamic string format template
2 string = "{:{fill}{align}{width}}"
3
4 # passing format codes as arguments
5 print(string.format('cat', fill='*', align='^', width=5))
6
7 # dynamic float format template
8 num = "{:{align}{width}.{precision}f}"
9
10 # passing format codes as arguments
11 print(num.format(123.236, align='<', width=8, precision=2))

Run 

Powered by DataCamp

When you run the program, the output will be:

* * c a t * *
1 2 3 . 2 4

Here,

https://www.programiz.com/python-programming/methods/string/format 11/15
3/20/2018 Python String format()

In the rst example, 'cat' is the positional argument is to be formatted. Likewise,


TUTORIAL EXAMPLES BUILT-IN FUNCTIONS
fill='*' , align='^' and width=5 are keyword arguments. 
In the template string, these keyword arguments are not retrieved as normal strings
to be printed but as the actual format codes fill, align and width .
The arguments replaces the corresponding named placeholders and the string 'cat' is
formatted accordingly.
Likewise, in the second example, 123.236 is the positional argument and, align, width
and precision are passed to the template string as format codes.

Extra formatting options with format()


format() also supports type-speci c formatting options like datetime's and complex number
formatting.

format() internally calls __format__() for datetime, while format() accesses the attributes of
the complex number.

You can easily override the __format__() method of any object for custom formatting.

Example 11: Type-speci c formatting with format() and


overriding __format__() method
script.py IPython Shell
1 import datetime
2 # datetime formatting
3 date = datetime.datetime.now()
4 print("It's now: {:%Y/%m/%d %H:%M:%S}".format(date))
5
6 # complex number formatting
7 complexNumber = 1+2j
8 print("Real part: {0.real} and Imaginary part: {0.imag}".format(complexNumber))
9
10 # custom __format__() method
11 class Person:
12 def __format__(self, format):
13 if(format == 'age'):
14 return '23'
15 return 'None'
16
17 print("Adam's age is: {:age}".format(Person()))

Run 

Powered by DataCamp

When you run the program, the output will be:

It's now: 2016/12/02 04:16:28


Real part: 1.0 and Imaginary part: 2.0
Adam's age is: 23

https://www.programiz.com/python-programming/methods/string/format 12/15
3/20/2018 Python String format()

TUTORIAL EXAMPLES BUILT-IN FUNCTIONS 


Here,

For datetime:
Current datetime is passed as a positional argument to the format() method.
And, internally using __format__() method, format() accesses the year, month, day,
hour, minutes and seconds.
For complex numbers:
1+2j is internally converted to a ComplexNumber object.
Then accessing its attributes real and imag , the number is formatted.
Overriding __format__():
Like datetime, you can override your own __format__() method for custom formatting
which returns age when accessed as {:age}

You can also use object's __str__() and __repr__() functionality with shorthand notations
using format().

Like __format__(), you can easily override object's __str__() and __repr_() methods.

Example 12: __str()__ and __repr()__ shorthand !r and !s


using format()
script.py IPython Shell
1 # __str__() and __repr__() shorthand !r and !s
2 print("Quotes: {0!r}, Without Quotes: {0!s}".format("cat"))
3
4 # __str__() and __repr__() implementation for class
5 class Person:
6 def __str__(self):
7 return "STR"
8 def __repr__(self):
9 return "REPR"
10
11 print("repr: {p!r}, str: {p!s}".format(p=Person()))

Run 

Powered by DataCamp

When you run the program, the output will be:

Quotes: 'cat', Without Quotes: cat


repr: REPR, str: STR

https://www.programiz.com/python-programming/methods/string/format 13/15
3/20/2018 Python String format()

Want to learn more Python Data Science? Head over to DataCamp and try
forFUNCTIONS
TUTORIAL EXAMPLES BUILT-IN 
their free Python Tutorial

String Methods
Python String capitalize()

Python String center()

Python String casefold()

Python String count()

Python String endswith()

Python String expandtabs()

Python String encode()

Python String nd()

Python String format()

Python String index()

Python String isalnum()

Python String isalpha()

Python String isdecimal()

Python String isdigit()

Python String isidenti er()

https://www.programiz.com/python-programming/methods/string/format 14/15
3/20/2018 Python String format()

Python String islower()


TUTORIAL EXAMPLES BUILT-IN FUNCTIONS 

Receive the latest tutorial to improve your programming skills.

Enter Email Address* Join

Get Latest Updates on Programiz

Enter Your Email

Subscribe

ABOUT
CONTACT
ADVERTISE

C PROGRAMMING
C++ PROGRAMMING
R PROGRAMMING

Copyright © by Programiz | All rights reserved | Privacy Policy

https://www.programiz.com/python-programming/methods/string/format 15/15

You might also like