The Wayback Machine - https://web.archive.org/web/20240906212424/https://www.geeksforgeeks.org/python-string-format-method/
Open In App

Python String format() Method

Last Updated : 09 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The format() method is a powerful tool that allows developers to create formatted strings by embedding variables and values into placeholders within a template string. This method offers a flexible and versatile way to construct textual output for a wide range of applications. Python string format() function has been introduced for handling complex string formatting more efficiently. Sometimes we want to make generalized print statements in that case instead of writing print statements every time we use the concept of formatting.

Python String Format() Syntax

Syntax: { }.format(value)

Parameters: 

  • value : Can be an integer, floating point numeric constant, string, characters or even variables.

Returntype: Returns a formatted string with the value passed as parameter in the placeholder position. 

String Format() in Python Example

A simple demonstration of Python String format() Method in Python.

Python
name = "Ram"
age = 22
message = "My name is {0} and I am {1} years \
                    old. {1} is my favorite \
                    number.".format(name, age)
print(message)

Output

My name is Ram and I am 22 years old. 22 is my favorite number.

Using .Format() Method

This method of the built-in string class provides functionality for complex variable substitutions and value formatting. This new formatting technique is regarded as more elegant. The general syntax of format() method is string.format(var1, var2,…). Here we will try to understand how to Format A String That Contains Curly Braces In Python

Python
txt = "I have {an:.2f} Rupees!"
print(txt.format(an = 4))

Output

I have 4.00 Rupees!

Using a Single Formatter

In this example, we will use the string bracket notation program to demonstrate the str. format() method. Formatters work by putting in one or more replacement fields and placeholders defined by a pair of curly braces { } into a string and calling the str.format().

Python
# using format option in a simple string
print("{}, A computer science portal for geeks."
      .format("GeeksforGeeks"))

# using format option for a
# value stored in a variable
str = "This article is written in {}"
print(str.format("Python"))

# formatting a string using a numeric constant
print("Hello, I am {} years old !".format(18))

Output

GeeksforGeeks, A computer science portal for geeks.
This article is written in Python
Hello, I am 18 years old!

String format() with multiple placeholders

Multiple pairs of curly braces can be used while formatting the string in Python. Let’s say another variable substitution is needed in the sentence, which can be done by adding a second pair of curly braces and passing a second value into the method. Python will replace the placeholders with values in order. 

Syntax : { } { } .format(value1, value2)

Parameters :  (value1, value2) : Can be integers, floating point numeric constants, strings, characters and even variables. Only difference is, the number of values passed as parameters in format() method must be equal to the number of placeholders created in the string.

Errors and Exceptions : 

IndexError : Occurs when string has an extra placeholder, and we didn’t pass any value for it in the format() method. Python usually assigns the placeholders with default index in order like 0, 1, 2, 3…. to access the values passed as parameters. So when it encounters a placeholder whose index doesn’t have any value passed inside as parameter, it throws IndexError. 

Python program using multiple placeholders to demonstrate str.format() method.

Python
# Multiple placeholders in format() function
my_string = "{}, is a {} science portal for {}"
print(my_string.format("GeeksforGeeks", "computer", "geeks"))

# different datatypes can be used in formatting
print("Hi ! My name is {} and I am {} years old"
      .format("User", 19))

# The values passed as parameters
# are replaced in order of their entry
print("This is {} {} {} {}"
      .format("one", "two", "three", "four"))

Output

GeeksforGeeks, is a computer science portal for geeks
Hi! My name is User and I am 19 years old
This is one two three four

String format() IndexError

Python program demonstrating Index error number of placeholders is four but there are only three values passed.

Python
# parameters in format function.
my_string = "{}, is a {} {} science portal for {}"

print(my_string.format("GeeksforGeeks", "computer", "geeks"))

Output

IndexError: tuple index out of range

Formatting Strings using Escape Sequences

You can use two or more specially designated characters within a string to format a string or perform a command. These characters are called escape sequences. An Escape sequence in Python starts with a backslash (\). For example, \n is an escape sequence in which the common meaning of the letter n is literally escaped and given an alternative meaning – a new line.

Escape sequenceDescription     Example      
\nBreaks the string into a new lineprint(‘I designed this rhyme to explain in due time\nAll I know’)
\tAdds a horizontal tabprint(‘Time is a \tvaluable thing’)
\\Prints a backslashprint(‘Watch it fly by\\as the pendulum swings’)
\’   Prints a single quoteprint(‘It doesn\’t even matter how hard you try’)
\”    Prints a double quoteprint(‘It is so\”unreal\”‘)
\amakes a sound like a bellprint(‘\a’) 

Formatters with Positional and Keyword Arguments

When placeholders { } are empty, Python will replace the values passed through str.format() in order. The values that exist within the str.format() method are essentially tuple data types and each individual value contained in the tuple can be called by its index number, which starts with the index number 0. These index numbers can be passed into the curly braces that serve as the placeholders in the original string.

Syntax : {0} {1}.format(positional_argument, keyword_argument)

Parameters : (positional_argument, keyword_argument)

  • Positional_argument can be integers, floating point numeric constants, strings, characters and even variables. 
  • Keyword_argument is essentially a variable storing some value, which is passed as parameter.

Example: To demonstrate the use of formatters with positional key arguments.

Python
# Positional arguments
# are placed in order
print("{0} love {1}!!".format("GeeksforGeeks",
                              "Geeks"))

# Reverse the index numbers with the
# parameters of the placeholders
print("{1} love {0}!!".format("GeeksforGeeks",
                              "Geeks"))


print("Every {} should know the use of {} {} programming and {}"
      .format("programmer", "Open", "Source",
              "Operating Systems"))


# Use the index numbers of the
# values to change the order that
# they appear in the string
print("Every {3} should know the use of {2} {1} programming and {0}"
      .format("programmer", "Open", "Source", "Operating Systems"))


# Keyword arguments are called
# by their keyword name
print("{gfg} is a {0} science portal for {1}"
      .format("computer", "geeks", gfg="GeeksforGeeks"))

Output

GeeksforGeeks love Geeks!! 
Geeks love GeeksforGeeks!!
Every programmer should know the use of Open Source programming and Operating Systems
Every Operating Systems should know the use of Source Open programming and programmer
GeeksforGeeks is a computer science portal for geeks

Type Specifying In Python

More parameters can be included within the curly braces of our syntax. Use the format code syntax {field_name: conversion}, where field_name specifies the index number of the argument to the str.format() method, and conversion refers to the conversion code of the data type.

Using %s – string conversion via str() prior to formatting

Python
print("%20s" % ('geeksforgeeks', ))
print("%-20s" % ('Interngeeks', ))
print("%.5s" % ('Interngeeks', ))

Output

geeksforgeeks
Interngeeks
Inter

Using %c– character  prior to formatting

Python
type = 'bug'

result = 'troubling'

print('I wondered why the program was %s me. Then\
it dawned on me it was a %s .' %
      (result, type))

Output

I wondered why the program was troubling me. Thenit dawned on me it was a bug .

Using %i signed decimal integer and %d signed decimal integer(base-10) prior to formatting

Python
match = 12000

site = 'Amazon'

print("%s is so useful. I tried to look\
up mobile and they had a nice one that cost %d rupees." % (site, match))

Output

Amazon is so useful. I tried to lookup mobile and they had a nice one that cost 12000 rupees.

Another useful Type Specifying 

  • %u unsigned decimal integer
  • %o octal integer
  • f – floating-point display
  • b – binary number
  • o – octal number
  • %x – hexadecimal with lowercase letters after 9
  • %X– hexadecimal with uppercase letters after 9
  • e – exponent notation

You can also specify formatting symbols. The only change is using a colon (:) instead of %.

For example, instead of %s use {:s} and instead of %d use (:d}

Syntax : String {field_name:conversion} Example.format(value)
Errors and Exceptions : 
ValueError : Error occurs during type conversion in this method. 

Convert base-10 decimal integers to floating-point numeric constants 

Python
print("This site is {0:f}% securely {1}!!".
      format(100, "encrypted"))

# To limit the precision
print("My average of this {0} was {1:.2f}%"
      .format("semester", 78.234876))

# For no decimal places
print("My average of this {0} was {1:.0f}%"
      .format("semester", 78.234876))

# Convert an integer to its binary or
# with other different converted bases.
print("The {0} of 100 is {1:b}"
      .format("binary", 100))

print("The {0} of 100 is {1:o}"
      .format("octal", 100))

Output

This site is 100.000000% securely encrypted!!
My average of this semester was 78.23%
My average of this semester was 78%
The binary of 100 is 1100100
The octal of 100 is 144

Type Specifying Errors

Demonstrate ValueError while doing forced type-conversions

Python
# When explicitly converted floating-point
# values to decimal with base-10 by 'd'
# type conversion we encounter Value-Error.
print("The temperature today is {0:d} degrees outside !"
      .format(35.567))

# Instead write this to avoid value-errors
''' print("The temperature today is {0:.0f} degrees outside !"
                                            .format(35.567))'''

Output

ValueError: Unknown format code 'd' for object of type 'float'

Padding Substitutions or Generating Spaces

Demonstration of spacing when strings are passed as parameters

By default, strings are left-justified within the field, and numbers are right-justified. We can modify this by placing an alignment code just following the colon.

<   :  left-align text in the field
^ : center text in the field
> : right-align text in the field
Python
# To demonstrate spacing when
# strings are passed as parameters
print("{0:4}, is the computer science portal for {1:8}!"
      .format("GeeksforGeeks", "geeks"))

# To demonstrate spacing when numeric
# constants are passed as parameters.
print("It is {0:5} degrees outside !"
      .format(40))

# To demonstrate both string and numeric
# constants passed as parameters
print("{0:4} was founded in {1:16}!"
      .format("GeeksforGeeks", 2009))


# To demonstrate aligning of spaces
print("{0:^16} was founded in {1:<4}!"
      .format("GeeksforGeeks", 2009))

print("{:*^20s}".format("Geeks"))

Output : 

GeeksforGeeks, is the computer science portal for geeks   !
It is 40 degrees outside!
GeeksforGeeks was founded in 2009!
GeeksforGeeks was founded in 2009 !
*******Geeks********

Applications 

Formatters are generally used to Organize Data. Formatters can be seen in their best light when they are being used to organize a lot of data in a visual way. If we are showing databases to users, using formatters to increase field size and modify alignment can make the output more readable.

Example: To demonstrate the organization of large data using format()

Python
# which prints out i, i ^ 2, i ^ 3,
#  i ^ 4 in the given range

# Function prints out values
# in an unorganized manner
def unorganized(a, b):
    for i in range(a, b):
        print(i, i**2, i**3, i**4)

# Function prints the organized set of values
def organized(a, b):
    for i in range(a, b):

        # Using formatters to give 6
        # spaces to each set of values
        print("{:6d} {:6d} {:6d} {:6d}"
              .format(i, i ** 2, i ** 3, i ** 4))

# Driver Code
n1 = int(input("Enter lower range :-\n"))
n2 = int(input("Enter upper range :-\n"))

print("------Before Using Formatters-------")

# Calling function without formatters
unorganized(n1, n2)

print()
print("-------After Using Formatters---------")
print()

# Calling function that contains
# formatters to organize the data
organized(n1, n2)

Output : 

Enter lower range :-
3
Enter upper range :-
10
------Before Using Formatters-------
3 9 27 81
4 16 64 256
5 25 125 625
6 36 216 1296
7 49 343 2401
8 64 512 4096
9 81 729 6561
-------After Using Formatters---------
3 9 27 81
4 16 64 256
5 25 125 625
6 36 216 1296
7 49 343 2401
8 64 512 4096
9 81 729 6561

Using a dictionary for string formatting 

Using a dictionary to unpack values into the placeholders in the string that needs to be formatted. We basically use ** to unpack the values. This method can be useful in string substitution while preparing an SQL query.

Python
introduction = 'My name is {first_name} {middle_name} {last_name} AKA the {aka}.'
full_name = {
    'first_name': 'Tony',
    'middle_name': 'Howard',
    'last_name': 'Stark',
    'aka': 'Iron Man',
}

# Notice the use of "**" operator to unpack the values.
print(introduction.format(**full_name))

Output:

My name is Tony Howard Stark AKA the Iron Man.

Python format() with list

Given a list of float values, the task is to truncate all float values to 2 decimal digits. Let’s see the different methods to do the task.

Python
# Python code to truncate float
# values to 2 decimal digits.
  
# List initialization
Input = [100.7689454, 17.232999, 60.98867, 300.83748789]
  
# Using format
Output = ['{:.2f}'.format(elem) for elem in Input]
  
# Print output
print(Output)

Output

['100.77', '17.23', '60.99', '300.84']

Python String format() Method – FAQs

What is format() in Python?

The format() function in Python is a built-in function that allows for complex variable substitutions and value formatting. This function provides a way to format strings, often for output, which is more flexible and powerful than the older way of formatting using the % operator. It can be used to control formatting options such as alignment, width, precision, and various type-specific options.

Example:

text = "The price of {0} is approximately ${1:.2f}."
formatted_text = format(text.format("apple", 0.245))
print(formatted_text)

This will output: The price of apple is approximately $0.25.

What is the __format__ Method in Python?

The __format__ method in Python is a special (dunder) method that defines how an object should be formatted when it’s passed to the format() function. You can define custom __format__ methods to control how objects of a class are represented in formatted strings.

Example of Custom __format__:

class Product:
def __init__(self, name, price):
self.name = name
self.price = price

def __format__(self, format_spec):
if format_spec == 'n':
return self.name
return f"{self.name} costs ${self.price:.2f}"

product = Product("Book", 29.99)
print("{:n}".format(product)) # Custom format code 'n'
print("{}".format(product))

This customizes the formatting behavior for instances of Product.

What Does strip() Do in Python?

The strip() method in Python is used to remove leading and trailing whitespace from a string. It can also be used to remove other specified characters from the beginning and the end of the string by passing the characters as arguments to the method.

Example:

text = "   hello world   "
print(text.strip()) # Removes spaces
print(text.strip(' hld')) # Removes 'h', 'l', 'd' and spaces at both ends

This results in "hello world" and "ello wor" respectively.

Does format() Return a String?

Yes, the format() function always returns a string. Regardless of the input types provided to format(), the output is formatted as a string according to the format specifiers provided.

What is the Use of Format Operator in Python?

The format operator % in Python is used for string formatting. It lets you construct strings by embedding variables enclosed in a format specifier like %s for strings, %d for integers, and so on. The format operator can handle simple positional formatting which is less versatile compared to the newer str.format() method or f-strings in Python 3.6 and above.

Example using Format Operator:

name = "Alice"
age = 30
print("Name: %s, Age: %d" % (name, age))

This outputs: Name: Alice, Age: 30.



Previous Article
Next Article

Similar Reads

Python String Formatting - How to format String?
String formatting allows you to create dynamic strings by combining variables and values. In this article, we will discuss about 5 ways to format a string. You will learn different methods of string formatting with examples for better understanding. Let's look at them now! How to Format Strings in PythonThere are five different ways to perform stri
10 min read
What does %s mean in a Python format string?
The % symbol is used in Python with a large variety of data types and configurations. %s specifically is used to perform concatenation of strings together. It allows us to format a value inside a string. It is used to incorporate another string within a string. It automatically provides type conversion from value to string. The %s operator is put w
3 min read
Convert datetime string to YYYY-MM-DD-HH:MM:SS format in Python
In this article, we are going to convert the DateTime string into the %Y-%m-%d-%H:%M:%S format. For this task strptime() and strftime() function is used. strptime() is used to convert the DateTime string to DateTime in the format of year-month-day hours minutes and seconds Syntax: datetime.strptime(my_date, "%d-%b-%Y-%H:%M:%S") strftime() is used t
2 min read
Convert String to currency format
Given a number N. Convert N into an Indian currency format. For more understanding, please look into examples. Examples: Input: N = 1000000Output: Rs 10, 00, 000 Input: N = 1500Output: Rs 1, 500 Approach: Steps involved in the implementation of code: We need to check whether the length of the string is even or odd.If the length of the string is les
5 min read
Represent the fraction of two numbers in the string format
Given two integers representing the Numerator and Denominator of a fraction, return the fraction in string format. If the fractional part is repeating, enclose the repeating part in parentheses. Examples: Input: Numerator = 1, Denominator = 2 Output: "0.5" 1/2 = 0.5 with no repeating part. Input: Numerator = 50, Denominator = 22 Output: "2.(27)" 50
9 min read
Print string of odd length in 'X' format
Given a string of odd length, print the string X format.Examples : Input: 12345 Output: 1 5 2 4 3 2 4 1 5 Input: geeksforgeeks Output: g s e k e e k e s g f r o f r s g k e e e e k g s We strongly recommend you to minimize your browser and try this yourself first.The idea is to use two variables in a single loop, the first variable 'i' goes from le
15 min read
Encode an ASCII string into Base-64 Format
Base 64 is an encoding scheme that converts binary data into text format so that encoded textual data can be easily transported over network un-corrupted and without any data loss. Base64 is used commonly in a number of applications including email via MIME, and storing complex data in XML. Problem with sending normal binary data to a network is th
15+ min read
Convert the column type from string to datetime format in Pandas dataframe
While working with data in Pandas, it is not an unusual thing to encounter time series data, and we know Pandas is a very useful tool for working with time-series data in Python.Let's see how we can convert a dataframe column of strings (in dd/mm/yyyy format) to datetime format. We cannot perform any time series-based operation on the dates if they
5 min read
PyQt5 - format() method for Progress bar
We can set the formatting and show text using setFormat method in Progress Bar, format method is used to get the formatting of the progress bar. Note : By default formatting of progress bar is '%p%' i.e used to print percentage, so if no specific formatting is set format method will return '%p%'. Syntax : bar.format() Argument : It takes no argumen
2 min read
Fast method to calculate inverse square root of a floating point number in IEEE 754 format
Given a 32-bit floating point number x stored in IEEE 754 floating point format, find the inverse square root of x, i.e., x-1/2.A simple solution is to do floating point arithmetic. Following is an example function. C/C++ Code #include &lt;bits/stdc++.h&gt; using namespace std; float InverseSquareRoot(float x) { return 1/sqrt(x); } int main() { cou
4 min read
Pandas Series dt.to_period() Method | Convert DateTime to Period Format
The Pandas dt.to_period() method converts the underlying data of the given Series object to PeriodArray/Index at a particular frequency. It is used to convert a DateTime series to a period series with a specific frequency, such as daily, monthly, quarterly, or yearly periods. Example C/C++ Code import pandas as pd sr = pd.Series(['2012-12-31', '201
2 min read
Pandas Series dt.strftime() Method | Change Date Format in Series
The dt.strftime() method converts the datetime objects in the Pandas Series to a specified date format. The function returns an index of formatted strings specified by date_format, which supports the same string format as the Python standard library. Example[GFGTABS] Python import pandas as pd sr = pd.Series([&#39;2012-12-31 08:45&#39;, &#39;2019-1
3 min read
Python program to convert time from 12 hour to 24 hour format
Given a time in 12-hour AM/PM format, convert it to military (24-hour) time. Note : Midnight is 12:00:00 AM on a 12-hour clock and 00:00:00 on a 24-hour clock. Noon is 12:00:00 PM on 12-hour clock and 12:00:00 on 24-hour clock. Examples : Input : 11:21:30 PMOutput : 23:21:30Input : 12:12:20 AMOutput : 00:12:20How to Convert AM/PM to 24 Hour Time Wh
3 min read
Python | Pandas TimedeltaIndex.format
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas TimedeltaIndex.format() function render a string representation of the given TimedeltaIndex object. Syntax : TimedeltaIndex.forma
2 min read
Python program to print the dictionary in table format
Given a Dictionary. The task is to print the dictionary in table format. Examples: Input: {1: ["Samuel", 21, 'Data Structures'], 2: ["Richie", 20, 'Machine Learning'], 3: ["Lauren", 21, 'OOPS with java'], }Output: NAME AGE COURSE Samuel 21 Data Structures Richie 20 Machine Learning Lauren 21 OOPS with java Method 1: Displaying results by iterating
2 min read
Vulnerability in str.format() in Python
Prerequisites: Python - format() function str.format() is one of the string formatting methods in Python3, which allows multiple substitutions and value formatting. This method lets us concatenate elements within a string through positional formatting. It seems quite a cool thing. But the vulnerability comes when our Python app uses str.format in t
2 min read
Python IMDbPY – Series Information in XML format
In this article we will see how we can get the company information in the XML format. Extensible Markup Language (XML) is a markup language that defines a set of rules for encoding documents in a format that is both human-readable and machine-readable. Series object contains all the information about the all the episodes and seasons that has record
2 min read
Python IMDbPY – Company Information in XML format
In this article we will see how we can get the company information in the XML format. Extensible Markup Language (XML) is a markup language that defines a set of rules for encoding documents in a format that is both human-readable and machine-readable. Company object contains all the information about the company which is related to film industry a
2 min read
Python IMDbPY – Person Information in XML format
In this article we will see how we can get the person information in the XML format. Extensible Markup Language (XML) is a markup language that defines a set of rules for encoding documents in a format that is both human-readable and machine-readable. Person object contains all the information about the person which is related to film industry and
2 min read
Python IMDbPY – Movies Information in XML format
In this article we will see how we can get the movies information in the XML format. Extensible Markup Language (XML) is a markup language that defines a set of rules for encoding documents in a format that is both human-readable and machine-readable. In order to get this we have to do the following 1. Import the IMDbPY module 2. Create a instance
2 min read
Convert an image into jpg format using Pillow in Python
Let us see how to convert an image into jpg format in Python. The size of png is larger when compared to jpg format. We also know that some applications might ask for images of smaller sizes. Hence conversion from png(larger ) to jpg(smaller) is needed. For this task we will be using the Image.convert() method of the Pillow module. Algorithm : Impo
2 min read
Formatting containers using format() in Python
Let us see how to format containers that were accessed through __getitem__ or getattr() using the format() method in Python. Accessing containers that support __getitem__a) For Dictionaries C/C++ Code # creating a dictionary founder = {'Apple': 'Steve Jobs', 'Microsoft': 'Bill Gates'} # formatting print('{f[Microsoft]} {f[Apple]}'.format(f = founde
1 min read
Determining file format using Python
The general way of recognizing the type of file is by looking at its extension. But this isn't generally the case. This type of standard for recognizing file by associating an extension with a file type is enforced by some operating system families (predominantly Windows). Other OS's such as Linux (and its variants) use the magic number for recogni
3 min read
Converting a 10 digit phone number to US format using Regex in Python
Text preprocessing is one of the most important tasks in Natural Language Processing. You may want to extract number from a string. Writing a manual script for such processing task requires a lot of effort and at most times it is prone to errors. Keeping in view the importance of these preprocessing tasks, the concept of Regular Expression have bee
1 min read
How to change the Pandas datetime format in Python?
Prerequisites: Pandas The date-time default format is "YYYY-MM-DD". Hence, December 8, 2020, in the date format will be presented as "2020-12-08". The datetime format can be changed and by changing we mean changing the sequence and style of the format. Function used strftime() can change the date format in python. Syntax: strftime(format) Where, fo
1 min read
How to Format date using strftime() in Python ?
In this article, we will see how to format date using strftime() in Python. localtime() and gmtime() returns a tuple representing a time and this tuple is converted into a string as specified by the format argument using python time method strftime(). Syntax: time.strftime(format[, sec]) sec: This is the time in number of seconds to be formatted. f
2 min read
Parsing and converting HTML documents to XML format using Python
In this article, we are going to see how to parse and convert HTML documents to XML format using Python. It can be done in these ways: Using Ixml module.Using Beautifulsoup module.Method 1: Using the Python lxml library In this approach, we will use Python's lxml library to parse the HTML document and write it to an encoded string representation of
3 min read
Format SQL in Python with Psycopg's Mogrify
Psycopg, the Python PostgreSQL driver, includes a very useful mechanism for formatting SQL in python, which is mogrify. After parameters binding, returns a query string. The string returned is the same as what SQLwas sent to the database if you used the execute() function or anything similar. One may use the same inputs for mogrify() as you would f
2 min read
Save API data into CSV format using Python
In this article, we are going to see how can we fetch data from API and make a CSV file of it, and then we can perform various stuff on it like applying machine learning model data analysis, etc. Sometimes we want to fetch data from our Database Api and train our machine learning model and it was very real-time by applying this method we can train
6 min read
Python Program to Convert a Number into 32-Bit Binary Format
Binary representation is a fundamental concept in computer science, and converting numbers into binary format is a common task for programmers. In this article, we will explore some simple and generally used methods to convert a number into a 32-bit binary format using Python. Each method provides a unique approach to achieve the same result. Conve
3 min read