How to use format function in Python?

This recipe helps you use format function in Python

Format function in python

In this tutorial, we are going to see how to use the format function in python and explore different ways the format function can be used.

In python, string format() method formats a given string into a pleasant output by inserting some specified values into the string's placeholder. The placeholder is defined using curly brackets: {}.

There are a lot of ways in which we can use the format function. Let us see them one by one in detail.

Access House Price Prediction Project using Machine Learning with Source Code

1. Using Positional and Keyword Arguments

The format() method can have any number of arguments. The format() parameters are of two types. One is positional parameters and the other one is keyword parameters.

Syntax:

'string'.format(p0,p1,p2,....,k0=v0,k1=v1,...)

In the above syntax--p0,p1,p2 are positional parameters and k0,k1 are keyword parameters while v0,v1 are respective values to the keyword parameters.

Positional parameters are place holders in the string that can be filled with specific positional index that can access the list of parameters.

For Example,

print("Hello {0}, Your bill amount is {1} dollars".format('Shyam',15))

Output

Hello Shyam, Your bill amount is 15 dollars

As mentioned before, the curly braces are just placeholders for the arguments to be placed. In the above example, Since 'Shyam' is the 0th argument, it is placed in {0} and since 15 is the 1st argument, it is placed in {1}.

Positional arguments works even when the positions are not mentioned inside the curly braces. Leaving empty curly braces is equivalent to using positional arguments.

Keyword parameters are place holders in the format string can be filled with keywords. Parameters contains the values for the keywords used. For example,

print("Hello {name}, Your bill amount is {amnt} dollars".format(amnt=15,name='Shyam'))

Output

Hello Shyam, Your bill amount is 15 dollars

Although you can also combine both positional and keyword arguments in the same string, it is not the best practice to follow.

2. Using Dictionaries

You can also use dictionaries to format the string in the following manner.

# define Salary dictionary
salary = {'amnt': 153000, 'name': 'Adam'}
print("Hello {s[name]},Your salary is:{s[age]}".format(s=salary))

Output



Hello Shyam, Your salary is:153000

3. Using Classes

Just like dictionaries, Classes can also be used inside the format function as shown below.


# define Salary class
class Salary:
    amnt = 153000
    name = "Shyam"

print("Hello {s.name}, Your salary is:{s.amnt}".format(s=Salary())) 

Output


Hello Shyam, Your salary is:153000

4. Using Specifiers

We can format numbers using specifiers given below.

Type Description
d Integer
f Float
b Binary
o Octal
x Hexadecimal
e Exponential
% Percentage

Here are a few examples!


# integer arguments
print("Your account balance is:{:d}".format(13500))

# float arguments
print("Your account balance is:{:f}".format(13524.368))

# float corrected to 2 decimal places 
print("Your account balance is:{:.2f}".format(13524.368))

# octal, binary and hexadecimal format
print("binary: {0:b}, octal: {0:o}, hexa: {0:x}".format(12))

Output


Your account balance is:13500
Your account balance is:13524.368 
Your account balance is:13524.37
binary: 1100, octal: 14, hexa: c

5. Formatting with alignment

By default, Numbers are right aligned and strings are left aligned. To impose specific alignment with certain width, we use the following operators mentioned below

Type Description
< Left aligned
> Right aligned
^ Centered aligned

Here are a few examples!


# string padding with left alignment
print("{:5}".format("Mug"))

# string padding with right alignment
print("{:>5}".format("Mug"))

# string padding with center alignment
print("{:^5}".format("Mug"))

Output


Mug  
  Mug
 Mug 

Hope this tutorial was useful! Thanks for the read

What Users are saying..

profile image

Abhinav Agarwal

Graduate Student at Northwestern University
linkedin profile url

I come from Northwestern University, which is ranked 9th in the US. Although the high-quality academics at school taught me all the basics I needed, obtaining practical experience was a challenge.... Read More

Relevant Projects

Time Series Forecasting Project-Building ARIMA Model in Python
Build a time series ARIMA model in Python to forecast the use of arrival rate density to support staffing decisions at call centres.

Build a Review Classification Model using Gated Recurrent Unit
In this Machine Learning project, you will build a classification model in python to classify the reviews of an app on a scale of 1 to 5 using Gated Recurrent Unit.

MLOps Project on GCP using Kubeflow for Model Deployment
MLOps using Kubeflow on GCP - Build and deploy a deep learning model on Google Cloud Platform using Kubeflow pipelines in Python

ML Model Deployment on AWS for Customer Churn Prediction
MLOps Project-Deploy Machine Learning Model to Production Python on AWS for Customer Churn Prediction

FEAST Feature Store Example for Scaling Machine Learning
FEAST Feature Store Example- Learn to use FEAST Feature Store to manage, store, and discover features for customer churn prediction machine learning project.

Tensorflow Transfer Learning Model for Image Classification
Image Classification Project - Build an Image Classification Model on a Dataset of T-Shirt Images for Binary Classification

Build a Multi-Class Classification Model in Python on Saturn Cloud
In this machine learning classification project, you will build a multi-class classification model in Python on Saturn Cloud to predict the license status of a business.

Word2Vec and FastText Word Embedding with Gensim in Python
In this NLP Project, you will learn how to use the popular topic modelling library Gensim for implementing two state-of-the-art word embedding methods Word2Vec and FastText models.

Learn to Build a Neural network from Scratch using NumPy
In this deep learning project, you will learn to build a neural network from scratch using NumPy

Loan Default Prediction Project using Explainable AI ML Models
Loan Default Prediction Project that employs sophisticated machine learning models, such as XGBoost and Random Forest and delves deep into the realm of Explainable AI, ensuring every prediction is transparent and understandable.