Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

String formatting with Python

String formatting, also known as String interpolation, is the process of inserting a custom string
or variable dynamically in predefined text – to provide a consolidated string. These are used to
simplify utilization of variables in printing messages and errors. These allows easy customization
during generating strings.

There are 3 standard ways to perform string formatting in Python:


1. Formatting with % Operator – The formatting is managed by modulo operator (%), also
known as string formatting operator. This method of formatting is also known as the
placeholder method. It is the oldest method of string formatting. It supports to insert
multiple strings at a time and also use variables to insert objects. A standard syntax for
inserting objects of different data types:
a. ‘%s’ for strings
b. ‘%d’ for integers
c. ‘%f’ for floating-point values
d. ‘%b’ for binary format
Amount = 1000
print('Raju has %d rupees in his %s' %(Amount, 'bank'))
Output: Raju has 1000 rupees in his bank

2. Format string using format() method – This 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(). In addition to the benefits of the placeholder method, the
str.format() method allows insert object by using index-based position and assigned
keywords. This is also helpful in reusing an inserted object to avoid duplication
num1 = 5
num2 = 7
print('The larger number of {a} and {b} is {b}, not {0:0.3f}'.format(6, a = num1, b =
num2))
Output: The larger number of 5 and 7 is 7, not 6.000

3. Format String using F-strings – This is the most advanced string formatting mechanism.
It is also known as Literal String Interpolation. Though the formatting technique is very
similar to str.format(), it is concise, convenient and simpler. It allows to insert arbitrary
Python expressions (like arithmetic operations) in it.
a=5
print(f'{a} is {a}. It is not {a * 2}, nor {a:0.2f}')
Output: 5 is 5. It is not 10, nor 5.00

Floating Number Formatting


Floating-point numbers are formatted by using a.bf – where ‘a’ is the minimum number of
digits to be present in the string and ‘b’ represents the number of digits to be displayed after
the decimal point. ‘f’ is the standard character representing floating number. Incase the total
count of digits in less than ‘a’ then the extra places are padded with white spaces. For modulo
operator it is used as %a.bf. With str.format() and f-string, it is used as {number:a.bf}

You might also like