Python format string

Python String formatting is a flexible way to concatenate strings. With Python String formatting, we concatenate elements within a string. It can be achieved through three different methods using:

  • %
  • {}.format
  • Template string

In this tutorial, we will see each of these in detail.

Python String Formatting Using %:

String formatting in Python using ‘%’ operator is similar to ‘printf’ in C programming language. The set of variables enclosed in a tuple with a ‘%’ operator can be concatenated with the normal text in the place of argument specifiers. Here is the list of basic argument specifiers:

  • %s-string
  • %d-integer
  • %f-float
  • %x-hexadecimal
  • %f-float

Single argument specifier:

Let’s see an example to understand the usage of string formatting in Python using a single specifier.

var = 12

print("String Representation: %s" %(var))
print("Integer Representation: %d" %(var))
print("Float Representation: %f" %(var))
print("Hexadecimal Representation: %x" %(var))
print("Octal Representation: %o" %(var))
String Representation: 12
Integer Representation: 12
Float Representation: 12.000000
Hexadecimal Representation: c
Octal Representation: 14

If you notice, here we are concatenating any data type with the string, without explicitly converting into a string. If you use a ‘+’ operator, you need to convert the variable to a string using ‘str’ if the variable is of the different data type.

Multiple argument specifiers:

If you have 2 or more variables to concatenate into a string, then enclose the variables in a tuple.

name='John Doe'
age=42

print('My name is %s and age is %d' %(name,age))
My name is John Doe and age is 42

Python String Formatting Using {}.format:

Syntax:

{}.format(value1,value2,etc.,)

{}-Placeholder. Place {} in the normal text/string where you want the values to be inserted.

.format(value)-values to be inserted in the placeholder.

Single placeholder:

name='John Doe'

print('My name is {}'.format(name))
My name is John Doe

Multiple placeholders:

You can use multiple placeholders in your string, those will be replaced with the values passed in the format method in the given order.

name='John Doe'
age=42

print('My name is {} and age is {}'.format(name,age))
My name is John Doe and age is 42
Errors:

While using multiple placeholders you need to be careful about the two things:

  • Values will be replacing the placeholders in the given order.
name='John Doe'
age=42

print('My name is {} and age is {}'.format(age,name))
My name is 42 and age is John Doe
  • The number of placeholders should match the number of values passed in the format.
name='John Doe'
age=42

print('My name is {} {} and age is {}'.format(age,name))
Traceback (most recent call last):
  File "sample.py", line 4, in <module>
    print('My name is {} {} and age is {}'.format(age,name))
IndexError: tuple index out of range

Positional arguments:

The examples we have seen so far are for positional arguments. Since we are mapping the placeholders with the values passed in the given order, we call it positional mapping.

The values we are passing in the format is of the type <tuple>. Since the tuple follows zero indexing, the numbers we use in the placeholders should start from 0.

name='John Doe'
age=42

print('My name is {0} and age is {1}'.format(name,age))

In Python 2.7 and above we can use the empty placeholders. We don’t need to specify the numbers since they will be auto-numbered internally. However, there are certain scenarios we might want to change the order. For such scenarios, we can use the numbers inside the placeholders. One such example is

name='John Doe'
age=42

print('My name is {1} and age is {0}'.format(age,name))
My name is John Doe and age is 42

In the above example, if we use empty placeholders, we won’t get the desired results, because the first placeholder will be replaced with age, and the second will be replaced with the name. The output will be like ‘My name is 42 and age is John Doe’. Since we are using the numbers inside the placeholders, the placeholder with a given number will be replaced by the corresponding tuple index value. In our example, the tuple of index 1 replaces the first placeholder, and the tuple of index 0 replaces the second placeholder.

Keyword arguments:

Instead of positional arguments, we can also use keyword arguments in the format function. Instead of numbers, we use key inside the placeholders and the value for the key is provided in the format function in the format key=value. The name of key is of your choice. Just make sure the name of the key in the placeholders matches the one given in the format function.

name='John Doe'
age=42

print('My name is {a} and age is {b}'.format(b=age,a=name))

Combination of positional and keyword arguments:

We can use both positional and keyword arguments in the function.

name='John Doe'
age=42

print('My name is {0} and age is {a}'.format(name,a=age))

Remember that, always keyword argument follows the positional argument, else we will get an error.

name='John Doe'
age=42

print('My name is {1} and age is {a}'.format(a=age,name))
  File "sample.py", line 4
    print('My name is {1} and age is {a}'.format(a=age,name))
                                                      ^
SyntaxError: positional argument follows keyword argument

Type specification:

Apart from numbers(indexes) and key names inside the placeholders we can also use conversion code when dealing with numerical values.

Syntax:
string{field_name:conversion}.format(value)

field_name: Index of the value passed in the format function.

conversion: conversion code of the data type. Below are the examples of conversion code:

  • 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
print('{0} value of 71 is: {1:s}'.format('String','71'))
print('{0} value of 71 is: {1:d}'.format('Integer',71))
print('{0} value of 71 is: {1:f}'.format('Float',71))
print('{0} value of 71 is: {1:X}'.format('Hexadecimal',71))
print('{0} value of 71 is: {1:b}'.format('Binary',71))
String value of 71 is: 71

Integer value

 of 71 is: 71
Float value of 71 is: 71.000000
Hexadecimal value of 71 is: 47
Binary value of 71 is: 1000111

With float representation, we can also specify how many digits we want to display after the decimal point.

print('{0} value of 71 is: {1:.2f}'.format('Float',71))
print('{0} value of 71 is: {1:.1f}'.format('Float',71))
print('{0} value of 71 is: {1:.0f}'.format('Float',71))
Float value of 71 is: 71.00
Float value of 71 is: 71.0
Float value of 71 is: 71

.2f/.1f/.0f specifies 2 digits, 1 digit, and 0 digits to display after the decimal point respectively.

Error:

We need to make sure that the conversion code and the data type of the value passed in the format function should match. Else we will get a value error.

print('{0} value of 71 is: {1:d}'.format('Integer','71'))
Traceback (most recent call last):
  File "sample.py", line 2, in <module>
    print('{0} value of 71 is: {1:d}'.format('Integer','71'))
ValueError: Unknown format code 'd' for object of type 'str'

Padding Spaces:

By default, strings are left justified and integers are right justified. But we can change this, by placing the alignment code followed by the colon. Here are the alignment codes:

<-align to the left.

>-align to the right.

^-align to the center.

print('{0} value of 71 is: {1:>16}'.format('String','71'))
String value of 71 is:               71

F-strings:

Python 3 has a new string formatting mechanism called F-strings. It’s represented by a letter ‘f’ preceding the string. Let’s see a few examples to understand the usage of F-strings.

name='John Doe'
age=42

print(f'My name is {name} and age is {age}')
details={'name':'John Doe','age':42}

print(f'My name is {details["name"]} and age is {details["age"]}')

Python String Formatting Using String Template:

The template class simplifies the syntax for output specification. Here, we use $ with a valid Python identifier to form a placeholder name.

from string import Template

t=Template("My Name is $name")
print(t.substitute({'name':'John Doe'}))

We can also import data from the list and print it using a template.

from string import Template
details=[("John Doe",42),('Jason',44)]

t=Template("Name: $name and Age: $age")
for i in details:
    print(t.substitute(name=i[0],age=i[1]))
Name: John Doe and Age: 42
Name: Jason and Age: 44
Error:

We will get a KeyError in case the placeholder is not supplied in a keyword argument or dictionary.

t=Template("My Name is $name and age is $age")
print(t.substitute({'name':'John Doe'}))
Traceback (most recent call last):
  File "sample.py", line 4, in <module>
    print(t.substitute({'name':'John Doe'}))
  File "C:\Users\Gopi\AppData\Local\Programs\Python\Python36-32\lib\string.py", line 126, in substitute

    return self.pattern.sub(convert, self.template)
  File "C:\Users\Gopi\AppData\Local\Programs\Python\Python36-32\lib\string.py", line 119, in convert
    return str(mapping[named])
KeyError: 'age'

Conclusion:

This tutorial covers the basic examples for string formatting in Python. Please check the docs for further detailed information.

Translate »