Python Sprintf: The Formatted String in Python

Python Sprintf: The Formatted String in Python

  1. Formatted String in Python
  2. Different Methods of Formatted String in Python

There isn’t the exact sprintf built-in function to print formatted strings, but thanks to Python, numerous methods exist to print formatted strings.

In this article, we will cover four sprintf like functionality in Python, including the % operator, format(), f-string, and a user-defined sprintf function, so let’s dive deep into it.

Formatted String in Python

String formatting is also addressed as string interpolation, where we can insert a custom value, string, or variable in the predefined text.

It is one of the preferred and readable methods for printing strings, including some values or results, which gives us the sprintf like functionality in Python.

We can also use mathematical expressions in the formatted strings. For example, let us say we have two values and want to add them to print a final result.

Code Example:

x = 3 
y = 4
print(f"The sum of {x} and {y} = {x+y}")    # formatted string
print("The sum of",x,"and",y, "=", (x+y))   # normal string

Output:

The sum of 3 and 4 = 7
The sum of 3 and 4 = 7

As we can see, the result of the above is the same, but the normal string is very junky; however, the formatted string is more readable, and it is easy for developers to write code using the formatted string.

Different Methods of Formatted String in Python

Pythons is a general-purpose programming language with a diverse open source community and continuous support which offers solutions and functionalities to developers to achieve any task in numerous ways depending upon the nature of the job and the particular scenario.

Similarly to using formatted strings, we have different methods that we can use to print formatting strings which we will discuss in this article one by one.

Formatted String Using the % Operator

It is one of the old techniques for formatted strings in Python and other programming languages. In Python, strings have a built-in operation accessible using the % operator, allowing us to do string formatting easily, similar to springf in C and C++.

Code Example:

name = "Zeeshan Afridi"
msg = "Hey! developers, it's %s." %name
print(msg)

Output:

Hey! developers, it's Zeeshan Afridi.

In the above code, %s alarms the compiler that I’m expecting a string at the end and as demonstrated, we have specified the string with the % operator as %name.

There are different format specifiers for different data types in string formatting.

Format Specifier Data Type Output
%c char It shows a Unicode character
%d integer Integer
%f Floating point Decimal number
%o integer (octal) Octal number
%s String It gives a string
%t Date and Time Data and time

Formatted String Using the format() Function in Python

The format() is a new method for formatting strings in Python, and it is introduced in Python 3.

It is a new style for formatting strings where we don’t need to remember the format specifiers and their sequence in the string; instead, we can use the format() at the end of the string and provide the arguments at the specified positions.

Code Example:

program = "BSSE"
cgpa = 3.2
student = 'Hi! I am a student of {}, and my CGPA is {}'.format(program, cgpa)
print(student)

Output:

Hi! I am a student of BSSE, and my CGPA is 3.2

In the above program, we have specified the positions where we wanted to insert a value with curly brackets {}, and at the end of the string student, we have used the .format() function and given it two arguments accordingly.

Formatted String Literal f-string in Python

Formatted string literal is also known as f-string, and it is included in Python 3.6 as a new string formatting method whose syntax is more readable and straightforward.

f-string has an excellent and unique feature that the other methods were missing out, and we can define the expressions and values inside the string.

There isn’t any need to use .format() at the end of the string. Let’s see an example of f-String in Python below.

Code Example:

my_fav_lang = "Python"
experience = 2

zeeshan = f'I love to code in {my_fav_lang}, and I have {experience} year experience in Python programming.'
print(zeeshan)

Output:

I love to code in Python, and I have 2 years of experience in Python programming.

Wow! the f-string is super easy and readable. Unlike the other two methods, we don’t need to use any other method or commas but only use f as a prefix for the string, and we are good to go.

How to Use sprintf in Python

sprintf stands for string print; basically, it is a built-in function in C and C++ programming language to print out a formatted string, and it stores the output on a char buffer specified in sprintf(). And there are different but similar ways in Python.

The sprintf isn’t a user-defined function in Python, but we can use the StringIO instance as a buffer. And unlike the sprintf, we must pass a string to the buf.write and the formatting method. The % is used for string formatting in this case.

Code Example:

import io
from io import StringIO

def sprintf(buf, fmt, *args):
    buf.write(fmt %args)
 
age = 24
fav_color = "Blue"

buf = io.StringIO()
sprintf(buf, "I'm %d years old, and my favourite colour is %s!", age, fav_color)

print(buf.getvalue())

Output:

I'm 24 years old, and my favourite colour is Blue!

If you get any ImportError for this program, install the required dependencies from your command line interface (CLI).

Zeeshan Afridi avatar Zeeshan Afridi avatar

Zeeshan is a detail oriented software engineer that helps companies and individuals make their lives and easier with software solutions.

LinkedIn

Related Article - Python String

  • Remove Commas From String in Python
  • Check a String Is Empty in a Pythonic Way
  • Convert a String to Variable Name in Python
  • Remove Whitespace From a String in Python
  • Extract Numbers From a String in Python
  • Convert String to Datetime in Python