Formatting Strings¶
Let us understand how we can replace placeholders in Python using different variations of formatting strings.* While we can concatenate strings, it will by default fail when we try to concatenate string with non string.
- Conventionally we tend to use
str
to convert the data type of the non-string values that are being concatenated to string. - From Python 3, they have introduced placeholders using
{}
with in a string. - We can replace the placeholders either by name or by position.
Using placeholders will improve the readability of the code and it is highly recommended.
In [1]:
print('Hello World')
Hello World
In [2]:
print('Hello' + ' ' + 'World')
Hello World
In [3]:
# This will fail as we are trying to concatenate 0 to a string
print('Hello' + 0 + 'World')
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Input In [3], in <cell line: 2>() 1 # This will fail as we are trying to concatenate 0 to a string ----> 2 print('Hello' + 0 + 'World') TypeError: can only concatenate str (not "int") to str
In [4]:
print('Hello' + str(0) + 'World')
Hello0World
In [5]:
i = 0
print('Hello' + str(i) + 'World')
Hello0World
In [6]:
# Replacing placeholders by name
i = 0
print(f'Hello{i}World')
Hello0World
In [7]:
# Replacing placeholders by name
print('Hello{i}World'.format(i=0))
Hello0World
In [8]:
# Replacing placeholders by position
print('Hello{}World'.format(0))
Hello0World
In [9]:
# Replacing placeholders by position
print('Hello{}World{}'.format(0, 1))
Hello0World1
In [ ]:
# These are the approaches which are commonly used
i = 0
s1 = f'str1: Hello{i}World'
print(s1)
s2 = 'str2: Hello{j}World'.format(j=i)
print(s2)
{note}
It is recommended to use place holder approach over concatenating using `+`.