You are on page 1of 16

Python String format()

The string.format() is one of the string formatting methods in Python3, it


formats the given string into a nicer output in Python, which allows multiple
substitutions and value formatting.

The syntax of format() method is:

str.format(*args, **kwargs)

(or)

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.

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.


This method lets us concatenate elements within a string through positional
formatting.

Using a Single Formatter:

Formatters work by putting in one or more replacement fields and placeholders


defined by a pair of curly braces { } into a string and calling the str.format().

The value we wish to put into the placeholders and concatenate with the string
passed as parameters into the format function.

Syntax: { }.format(value)

Parameters :

(value): Can be an integer, floating point numeric constant, string, characters or even
variables.

Return type : Returns a formatted string with the value passed as parameter in the
placeholder position.

Example 1:

print("{} is a free online encyclopedia, created and edited by volunteers around


the world".format("Wikipedia"))

# using format option for a value stored in a variable

str = "This article is written by {}"

print(str.format("Gouthami"))

# formatting a string using a numeric constant

print ("Ramya is {} years old".format(32))


Using Multiple Formatters:

Multiple pairs of curly braces can be used while formatting the string. Let’s say if another
variable substitution is needed in sentence, can be done by adding a second pair of curly
braces and passing a second value into the method. Python will replace the placeholders by
values in order.

Syntax: { } { } .format(value1, value2)

Parameters:

(value1, value2) : Can be integers, floating point numeric constants, strings, characters and
even variables. Only difference is, the number of values passed as parameters in format()
method must be equal to the number of placeholders created in the string.

Errors and Exceptions:

IndexError: Occurs when string has an extra placeholder and we didn’t pass any value for
it in the format() method. Python usually assigns the placeholders with default index in
order like 0, 1, 2, 3…. to acces the values passed as parameters. So when it encounters a
placeholder whose index doesn’t have any value passed inside as parameter, it throws
IndexError.

Example: Multiple placeholders in format() function

my_string = "{} provides a {} and also a {}"

print (my_string.format('Yahoo','web portal','search engine'))

print ("Hi! My name is {} and I am {} years old".format("Gouthami", 32))

# The values passed as parameters are replaced in order of their entry

print("This is {} {} {} {} {}".format("Alpha", "Beta", "Gamma", Delta","Epsilon"))


Formatters with Positional and Keyword Arguments:

When placeholders { } are empty, Python will replace the values passed through str.format()
in order.

The values that exist within the str.format() method are essentially tuple data types and
each individual value contained in the tuple can be called by its index number, which starts
with the index number 0.

These index numbers are placed inside or into the curly braces that serve as the
placeholders in the original string.

Syntax: {0} {1}.format(positional_argument, keyword_argument)

Parameters: (positional_argument, keyword_argument)

Positional_argument can be integers, floating point numeric constants, strings, characters


and even variables.

Keyword_argument is essentially a variable storing some value, which is passed as


parameter.

# Positional arguments are placed in order

print("{0} and {1}".format("Science","Arts"))

# Reverse the index numbers with the parameters of the placeholders

print("{1} and {0}".format("Arts","Science"))

print("Modern Web Developer should know {}, {}, {}, {}, {}, {} and
{}".format("HTML","CSS","JavaScript","Git","Framework","JSON","DevOps"))

print("Modern Web Developer should know {0}, {1}, {2}, {3}, {4}, {5} and
{6}".format("HTML","CSS","JavaScript","Git","Framework","JSON","DevOps"))

#Use the index numbers of the values to change the order they appear in the string

print("Modern Web Developer should know {4}, {2}, {5}, {6}, {0}, {1} and
{3}".format("HTML","CSS","JavaScript","Git","Framework","JSON","DevOps"))

# Keyword arguments are called by their keyword name

print("{html} is a {0} for creating {1}".format("markup language", "webpages",


html ="HyperText Markup Language"))
Type Specifying:

More parameters can be included within the curly braces of our syntax. Use the format
code syntax {field_name:conversion}, where field_name specifies the index number of the
argument to the str.format() method, and conversion refers to the conversion code of the
data type.

s – strings

d – decimal integers (base-10)

f – floating point display

c – character

b – binary

o – octal

x – hexadecimal with lowercase letters after 9

X – hexadecimal with uppercase letters after 9

e – exponent notation

Syntax:

String {field_name:conversion} Example.format(value)

Errors and Exceptions:

ValueError: Error occurs during type conversion in this method.

print("The temperature today is {0:.0f} degrees outside".format(35.567))

#Error

#When explicitly converted floating point values to decimal with base10 by 'd'
# type conversion we encounter Value-Error.

print("The temperature today is {0:d} degrees outside".format(35.567))

Traceback (most recent call last):

File "<pyshell#14>", line 1, in <module>

print("The temperature today is {0:d} degrees outside".format(35.567))

ValueError: Unknown format code 'd' for object of type 'float'


# Convert base-10 decimal integers to floating point numeric constants

print ("This site is {0:f}% securely {1}!!". format(100, "encrypted"))

# To limit the precision

print ("My average of this {0} was {1:.2f}%".format("semester", 78.234876))

# For no decimal places

print ("My average of this {0} was {1:.0f}%".format("semester", 78.234876))

# Convert an integer to its binary or with other different converted bases.

print("The {0} of 100 is {1:b}".format("binary", 100))

print("The {0} of 100 is {1:o}".format("octal", 100))

print("The {0} of 100 is {1:x}".format("Hexa-Decimal", 100))

print("{0:4}, is the capital city for {1:8}!".format("NewDelhi", "India"))

# To demonstrate spacing when numeric constants are passed as parameters.

print("It is {0:5} degrees outside !".format(40))

# To demonstrate both string and numeric constants passed as parameters

print("{0:4} was founded in {1:16}!".format("Wikipedia", 2001))

# To demonstrate aligning of spaces

print("{0:^16} was founded in {1:<4}!".format("Wikipedia", 2001))

print("{:*^20s}".format("Wikis")
How String format() works?

The format() reads the type of arguments passed to it and formats it according to the format
codes defined in the string.

For positional arguments:

print("Hello {0}, your balance is {1:9.3f}".format('Goutham',980.2346)))

Note: Argument index 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 "Goutham" and {1:9.3f} is placeholder for 980.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 "Goutham" 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 980.2346. Here, {1:9.3f} places 980.2346 in
its place and performs the operation 9.3f.

➢ “f” specifies the format is dealing with a float number. If not correctly specified, it will
give out an error.

➢ The part before the "." (9) specifies the minimum width/padding the number (980.2346)
can take.

➢ In this case, 980.2346 is allotted a minimum of 9 places including the ".".

➢ If no alignment option is specified, 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 off
outputting 235.
For keyword arguments:

print("Hello {ename}, your balance is


{salary:9.3f}".format(ename='Goutham',salary=980.2346))

Here, instead of just the parameters, we've used a key-value for the parameters. Namely,
ename='Goutham' and salary=980.2346.

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

Internally,

The placeholder {ename} is replaced by the value of ename = "Goutham". Since, it doesn't
contain any other format codes, "Goutham" is placed.

For the argument salary=980.2346, the placeholder {salary:9.3f} is replaced by the value
980.2346. But before replacing it, like previous example, it performs 9.3f operation on it.

This outputs 980.235. The decimal part is truncated after 3 places and remaining digits
are rounded off. Likewise, the total width is assigned 9 leaving two spaces to the left.

Basic formatting with format()

# default arguments

print("Hello {}, your balance is {}.".format("Goutham", 975.8762))

# positional arguments

print("Hello {0}, your balance is {1}.".format("Goutham", 975.8762))

# keyword arguments

print("Hello {ename}, your balance is


{salary}.".format(ename="Goutham",salary=975.8762))

# mixed arguments

print("Hello {0}, your balance is {salary}.".format("Goutham",salary=975.8762))


Numbers formatting with format()

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)

E Exponential notation (uppercase E)

f Displays fixed point number (Default: 6)

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

g General format. Rounds number to p significant 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


Simple number formatting

# integer arguments

print("The number is:{:d}".format(123))

# float arguments

print("The float number is:{:f}".format(123.4567898))

# octal, binary and hexadecimal format

print("bin: {0:b}, oct: {0:o}, hex: {0:x}".format(12))

Number formatting with padding for int and floats

# integer numbers with minimum width

print("{:5d}".format(12))

# width doesn't work for numbers longer than padding

print("{:2d}".format(1234))

# padding for float numbers

print("{:8.3f}".format(12.2346))

# integer numbers with minimum width filled with zeros

print("{:05d}".format(12))

# padding for float numbers filled with zeros

print("{:08.3f}".format(12.2346))

12

1234

12.235

00012

0012.235

In the first statement, {:5d} takes an integer argument and assigns a minimum width of 5.
Since, no alignment is specified, 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 thenumber.

Unlike integers, floats has both integer and decimal parts. And, the mininum width defined
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 off 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 fill the remaining places with zero, placing a zero before the format specifier
does this. It works both for integers and floats: {:05d} and {:08.3f}.
template_string = "Age={0:5d}Salary={1:8.2f}"

print(template_string.format(36,76425.869))

Number formatting for signed numbers

# show the + sign

print("{:+f} {:+f}".format(12.23, -12.23))

# show the - sign only

print("{:-f} {:-f}".format(12.23, -12.23))

# show space for + sign

print("{: f} {: f}".format(12.23, -12.23))

+12.230000 -12.230000

12.230000 -12.230000

12.230000 -12.230000

print("{0:c}".format(65))

target = 800

sales = 400

print("Target Achieved : {:%}".format(400/800))


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

Number formatting with left, right and center alignment

# integer numbers with right alignment

print("{:5d}".format(12))

print("{:>5d}".format(12))

# float numbers with center alignment

print("{:^10.3f}".format(12.2346))

# integer left alignment filled with zeros

print("{:<05d}".format(12))

# float numbers with center alignment

print("{:=8.3f}".format(-12.2346))

12

12

12.235

12000

- 12.235

Note: Left alignment filled with zeroes 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().

# string padding with left alignment

print("@{:5}@".format("cat"))

# string padding with left alignment

print("@{:<5}@".format("cat"))

# string padding with right alignment

print("@{:>5}@".format("cat"))

# string padding with center alignment

print("@{:^5}@".format("cat"))

# string padding with center alignment and '*' padding character

print("@{:*^5}@".format("cat"))

cat..

..cat

.cat.

*cat*

String formatting with format()

# truncating strings to 3 letters

print("{:.3}".format("caterpillar"))

# truncating strings to 3 letters and padding

print("{:5.3}".format("caterpillar"))

# truncating strings to 3 letters padding and center alignment

print("{:^5.3}".format("caterpillar"))

# truncating strings to 3 letters padding and right alignment

print("{:>5.3}".format("caterpillar"))

# truncating strings to 3 letters padding and right alignment

print("{:!>5.3}".format("caterpillar"))
cat

cat..

.cat.

..cat

!!cat

Formatting dictionary members using format()

person = {'age': 24, 'name': 'Ajay'}

# format dict

print("{p[name]}'s age is: {p[age]}".format(p=person))

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

person = {'age': 24, 'name': 'Ajay'}

# format dict

print("{name}'s age is: {age}".format(**person))

{:fillcharacter align width.truncate} for strings

print("{0:*>20.5s}".format('unitedstates'))

***************unite

{:fillcharacter align sign width.precision} for numbers

{indexordinal:fillcharacter align sign width.precision} numbers

{key:fillcharacter align sign width.precision} numbers

>>> print("{0:0>+9.2f}".format(452.676))

00+452.68

>>> print("{0:0>+9.2f}".format(-452.676))

00-452.68

>>> print("{0:0=+9.2f}".format(-452.676))

-00452.68

print("{0:A=+9.2f}".format(-452.676))

-AA452.68
Arguments as format codes using format()

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

# dynamic string format template

templatestring = "{:{fill}{align}{width}}"

# passing format codes as arguments

print(templatestring.format('cat', fill='*', align='^', width=7))

print(templatestring.format('cat', fill='*', align='^', width=5))

# dynamic float format template

num = "{:{align}{width}.{precision}f}"

# passing format codes as arguments

print(num.format(123.236, align='<', width=8, precision=2))

When you run the program, the output will be:

**cat**

*cat*

123.24..

Here,

1) In the first example, 'cat' is the positional argument is to be formatted.


Likewise, 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.

2) 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.
Applications:

Formatters are generally used to Organize Data. Formatters can be seen in their best light
when they are being used to organize a lot of data in a visual way. If we are showing
databases to users, using formatters to increase field size and modify alignment can make
the output more readable.

n1 = int(input("Enter lower range :- \n"))

n2 = int(input("Enter upper range :- \n"))

print("------Before Using Formatters-------")

# Data in unorganized manner

for i in range (n1, n2):

print ( i, i**2, i**3, i**4 )

print()

print("-------After Using Formatters---------")

print()

# Data in organized manner

for i in range (n1,n2):

print("{:6d} {:6d} {:6d} {:6d}".format(i, i ** 2, i ** 3, i ** 4))

You might also like