Python String Formatting

Python String Formatting

String formatting lets you inject items into a string rather than trying to chain items together using commas or string concatenation. As a quick comparison, consider:

player = ‘Thomas’
points = 33
‘Last night, ‘+player+’ scored ‘+str(points)+’ points.’ # concatenation
f’Last night, {player} scored {points} points.’ # string formatting

There are three ways to perform string formatting.

  • The oldest method involves placeholders using the modulo % character.
  • An improved technique uses the .format() string method.
  • The newest method, introduced with Python 3.6, uses formatted string literals, called f-strings.

Since you will likely encounter all three versions in someone else’s code, we describe each of them here.

Let’s explore the concept through jupyter notebook.

Datasciencelovers