How to interpolate data values into strings in Python?


We can interpolate data values into strings using various formats. We can use this to dedug code, produce reports, forms, and other outputs. In this topic, We will see three ways of formatting strings and how to interpolate data values into strings.

Python has three ways of formatting strings:

  • % - old school (supported in Python 2 and 3)

  • () - new style (Python 2.6 and up)

  • {} - f-strings (Python 3.6 and up)

Old style: %

The old style of string formatting has the form format_string % data. The format strings are nothing but interpolation sequences.

syntax
description
%s
string
%d
decimal
%x
hexa-int
%o
octal-int
%f
decimal-float
%e
exponential-float
%g
decimal or exponential-float
%%
literal %


# printing integer with % style type.
print('output \nprinting a number in string format %s' % 42)
print('printing a number in string decimal %d' % 42)
print('printing a number in string hexa-int %x' % 42)
print('printing a number in string exponential-float %g' % 42)

Output

printing a number in string format 42
printing a number in string decimal 42
printing a number in string hexa-int 2a
printing a number in string exponential-float 42

String and integer interpolation with old format %

The %s inside the string means to interpolate a string. The number of % appearances in the string needs to match the number of data items after the % that follows the string.

A single data item does right after that final %. Multiple data must be grouped into a tuple, see below example.

You can also add other values in the format string between the % and the type specifier to specify minimum and maximum widths, alignment, and the character filling.

1. + means right-align
2. - means left-align
3. . means separate minwidth and maxchars.
4. minwidth means mimimu field width to use
5. maxchars means how many characters/digits to print from the data value


player = 'Roger Federer'
country = 'Legend'
titles = 20

# note please try this only on Python 2. If you are running on Python3 output for below commands will vary a lot.

print('Output \n*** Tennis player %s From %s had won %d titles ' %(player,country,titles))
print('%s' % player) # print player
print('%5s' % player) # print firstname of player
print('%-7s' % player) # Last Name of player
print('%5.7s' % player) # Last Name of player with 5 leading spaces

Output

*** Tennis player Roger Federer From Legend had won 20 titles
Roger Federer
Roger Federer
Roger Federer
Roger F

String and integer interpolation with New style: {}

If you are using Python 3.5 or higher version, you can use the “new style” formatting described in below section.

“{}” formatting has the syntax as format_string.format(data).

Remember, arguments to the format() function need to be in the order as the {} placeholders in the format string. Somtimes for more read-ability you can pass dictionaires or named arguments to the format.

player = 'Roger Federer'
player = 'Roger_Federer'
country = 'Legend'
titles = 20

print('Output \n{}'.format(player))
print(' *** Tennis player {} From {} had won {} titles '.format(player,country,titles))

# positonal arguments
print(' *** Tennis player {1} From {2} had won {0} titles '.format(titles,player,country))

# named arguments
print(' *** Tennis player {player} From {country} had won {titles} titles '.format(player = 'Roger Federer',country = 'Legend',titles = 20))

# Dictionary arguments
print(' *** Tennis player {player} From {country} had won {titles} titles '.format(player = 'Roger Federer',country = 'Legend',titles = 20))

# alignment left '<' (default)
print(' *** Tennis player {} From {:<5s} had won {:<5d} titles '.format(player,country,titles))

# alignment left '<' (default)
print(' *** Tennis player {} From {:<5s} had won {:<5d} titles '.format(player,country,titles))

# alignment center '^'
print(' *** Tennis player {} From {:^10s} had won {:^10d} titles '.format(player,country,titles))

# alignment right '>'
print(' *** Tennis player {} From {:>10s} had won {:>10d} titles '.format(player,country,titles))


Output

Roger_Federer
*** Tennis player Roger_Federer From Legend had won 20 titles
*** Tennis player Roger_Federer From Legend had won 20 titles
*** Tennis player Roger Federer From Legend had won 20 titles
*** Tennis player Roger Federer From Legend had won 20 titles
*** Tennis player Roger_Federer From Legend had won 20 titles
*** Tennis player Roger_Federer From Legend had won 20 titles
*** Tennis player Roger_Federer From Legend had won 20 titles
*** Tennis player Roger_Federer From Legend had won 20 titles

String and integer interpolation with latest style: f-strings

f-strings appeared in Python 3.6, and soon became the recommended way of formatting strings. Personally I, use this format. To make an f-string:

1. Use letter f/F before the starting/initial quote.
2. Include variable names or expressions within curly brackets ({}) to get their values into the string.

player = 'Roger_Federer'
country = 'Legend'
titles = 20

print(f"Output \n *** Tennis player {player} From {country} had won {titles} titles ")
print(f" *** I hope {player} wins another {titles - 10} titles ")
print(f" {'*' * 3} Tennis player {player.upper()} From {country:.^10} had won {titles} titles")

Output

*** Tennis player Roger_Federer From Legend had won 20 titles
*** I hope Roger_Federer wins another 10 titles
*** Tennis player ROGER_FEDERER From ..Legend.. had won 20 titles

Now that we covered the basics, let us get into some real time problem and why I recommend start using Formatted strings.

titles = [
('federer', 20),
('nadal', 20),
('djokovic', 17),
]
print('Output\n')
for i, (player, titles) in enumerate(titles):
print('#%d: %-10s = %d' % (
i + 1,
player.title(),
round(titles)))

Output

#0: federer = 20
#1: nadal = 20
#2: djokovic = 17

Obviously, when sending a repor to higher up would not want to see the index starting at 0, they wanted to start at 1. Roger Federer being a legend of tennis, I personally wanted to represent him as #1 instead of #0.

Now to make that change, see how the read-abaility of the code changes while using older formats.

titles = [
('federer', 20),
('nadal', 20),
('djokovic', 17),
]
print('Output\n')
for i, (player, titles) in enumerate(titles):
print('#%d: %-10s = %d' % (
i + 1,
player.title(),
round(titles)))

Output

#1: Federer = 20
#2: Nadal = 20
#3: Djokovic = 17

To conclude, I have provided an example to show why f-strings are more easy to manage.

old_school_formatting = (
' Tennis Legeng is %(player)s, '
' %(player)s had won %(titles)s titles, '
'and he is from the country %(country)s.')
old_formatted = old_school_formatting % {
'player': 'Roger Federer',
'titles': 20,
'country': 'Swiss',
}
print('Output\n' + old_formatted)

Output

Tennis Legeng is Roger Federer, Roger Federer had won 20 titles, and he is from the country Swiss.


new_formatting = (
' Tennis Legeng is {player}, '
' {player} had won {titles} titles, '
'and he is from the country {country}')
new_formatted = new_formatting.format(
player= 'Roger Federer',
titles= 20,
country= 'Swiss',
)
print('Output\n' + new_formatted)

Output

Tennis Legeng is Roger Federer, Roger Federer had won 20 titles, and he is from the country Swiss

This style is slightly less noisy because it eliminates some quotes in the dictionary and quite a few characters in the format specifiers, but it’s hardly compelling.

Updated on: 10-Nov-2020

157 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements