/  Technology   /  String formatting in Python: % Operator vs str.format vs f-string literal
String formatting in Python

String formatting in Python: % Operator vs str.format vs f-string literal

 

In this article, let’s discuss three main approaches to string formatting in Python.

 

Old style String Formatting(% Operator):

In Python, strings have a built-in operation that can be accessed with the % operator using which formatting can be done very easily. It’s much similar to the printf function in C programming language, 

Example:

word= "Python"
'Hello I am learning %s by i2tutorials' %word

Output:

 

We use the %s format specifier here to inform Python where to substitute the value of word, which should be represented as a string.

 

There are other format specifiers available other than %s that let us control the output format. For example, we can convert numbers to hexadecimal notation using the %x format specifier or add whitespace padding to produce formatted tables and reports. 

 

The syntax changes a little bit if we want to make multiple substitutions to the same string.

Example:

word= "Python"
company="i2tutorials"

'Hello I am learning %s by i2tutorials' %word
'Hello I am learning %s %s' %(word, company)

Output:

 

New Style String Formatting(str.format):

The % formatting was technically superseded by “new style” formatting in Python 3 which however was later back-ported to Python 2.7. The “new style” string formatting doesn’t use the %-operator special syntax; rather it makes the syntax for string formatting more readable. Formatting is done by calling .format() function on a string object.

Example:

word= "Python"
'Hello I am learning {} by i2tutorials'.format(word)

Output:

 

String Interpolation / f-Strings:

A new string formatting approach was added in Python 3.6 called formatted string literals or “f-strings”. This string formatting enables us to embed Python expressions inside string constants. Look at the example below.

Example:

word= "Python"
f'Hello I am learning {word} by i2tutorials.'

Output:

 

The string constant is prefixed with the letter “f”, hence its name “f-strings.”. We can embed any Python expressions and do inline arithmetic with it. Look at the below example:

Example:

x = 8
y = 20
f'Eight plus Twenty is {x + y} and not {5 * (x + y)}.'

Output:

 

Formatted string literals are a Python parser feature that converts f-strings into a series of string constants and expressions which then get joined to build the final string.

 

Leave a comment