The Wayback Machine - https://web.archive.org/web/20240910125130/https://www.geeksforgeeks.org/string-formatting-in-python/
Open In App

Python String Formatting – How to format String?

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

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 Python

There are five different ways to perform string formatting in Python

  • Formatting with % Operator.
  • Formatting with format() string method.
  • Formatting with string literals, called f-strings.
  • Formatting with String Template Class
  • Formatting with center() string method.

So we will see the entirety of the above-mentioned ways, and we will also focus on which string formatting strategy is the best.

1. How to Format String using % Operator

It is the oldest method of string formatting. Here we use the modulo % operator. The modulo % is also known as the “string-formatting operator”.

Python Format String Using the % Operator

In the expression “The mangy, scrawny stray dog %s gobbled down” % ‘hurriedly’, the %s placeholder within the string is replaced by the value ‘hurriedly’.

Python
print("The mangy, scrawny stray dog %s gobbled down" %'hurriedly' + 
      "the grain-free, organic dog food.")

Output
The mangy, scrawny stray dog hurriedly gobbled downthe grain-free, organic dog food.

Injecting Multiple Strings using the modulo Operator

Here we are inserting multiple strings with the % operator.

Python
x = 'looked'

print("Misha %s and %s around"%('walked',x))

Output
Misha walked and looked around

Precision Handling in Python using % operator

Floating-point numbers use the format %a.bf. Here, a would be the minimum number of digits to be present in the string; these might be padded with white space if the whole number doesn’t have this many digits.

Close to this, bf represents how many digits are to be displayed after the decimal point. 

In this code, the string ‘The value of pi is: %5.4f’ contains a format specifier %5.4f. The %5.4f format specifier is used to format a floating-point number with a minimum width of 5 and a precision of 4 decimal places.

Python
print('The value of pi is: %5.4f' %(3.141592))

Output
The value of pi is: 3.1416

Multiple format conversion types

In the given code, the formatting string Python is converted to Integer and floating point with %d,%f.

Python
variable = 12 
string = "Variable as integer = %d \n\
Variable as float = %f" %(variable, variable)
print (string) 

Output
Variable as integer = 12 
Variable as float = 12.000000

Note: To know more about %-formatting, refer to String Formatting in Python using %

2. How to Format String using format() Method

Format() method was introduced with Python3 for handling complex string formatting more efficiently.

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(). The value we wish to put into the placeholders and concatenate with the string passed as parameters into the format function. 

Syntax: ‘String here {} then also {}’.format(‘something1′,’something2’)

Formatting String Python using format() Method

This code is using {} as a placeholder and then we have called.format() method on the ‘equal’ to the placeholder.

Python
print('We all are {}.'.format('equal'))

Output
We all are equal.

Index-based Insertion

In this code, curly braces {} with indices are used within the string ‘{2} {1} {0}’ to indicate the positions where the corresponding values will be placed.

Python
print('{2} {1} {0}'.format('directions',
                           'the', 'Read'))

Output
Read the directions

Insert object by Assigning Keywords

In this code, curly braces {} with named placeholders ({a}, {b}, {c}) are used within the string ‘a: {a}, b: {b}, c: {c}’ to indicate the positions where the corresponding named arguments will be placed.

Python
print('a: {a}, b: {b}, c: {c}'.format(a = 1,
                                      b = 'Two',
                                      c = 12.3))

Output
a: 1, b: Two, c: 12.3

Reuse the inserted objects

In this code, curly braces {} with named placeholders ({p}) are used within the string ‘The first {p} was alright, but the {p} {p} was tough.’ to indicate the positions where the corresponding named argument p will be placed.

Python
print(
    'The first {p} was alright, but the {p} {p} was tough.'.format(p='second'))

Output
The first second was alright, but the second second was tough.

Float Precision with the.format() Method

Syntax: {[index]:[width][.precision][type]}

The type can be used with format codes:

  • ‘d’ for integers
  • ‘f’ for floating-point numbers
  • ‘b’ for binary numbers
  • ‘o’ for octal numbers
  • ‘x’ for octal hexadecimal numbers
  • ‘s’ for string
  • ‘e’ for floating-point in an exponent format

Example:

Both the codes are doing string formatting. The first String is formatted with ‘%’ and the second String is formatted with .format().

Python
print('The valueof pi is: %1.5f' %3.141592)
print('The valueof pi is: {0:1.5f}'.format(3.141592))

Output
The valueof pi is: 3.14159
The valueof pi is: 3.14159

Note: To know more about str.format(), refer to format() function in Python

3. Understanding Python f-string

PEP 498 introduced a new string formatting mechanism known as Literal String Interpolation or more commonly as F-strings (because of the leading f character preceding the string literal). The idea behind f-String in Python is to make string interpolation simpler.

To create an f-string in Python, prefix the string with the letter “f”. The string itself can be formatted in much the same way that you would with str. format(). F-strings provide a concise and convenient way to embed Python expressions inside string literals for formatting.

String Formatting with F-Strings

In this code, the f-string f”My name is {name}.” is used to interpolate the value of the name variable into the string.

Python
name = 'Ele'
print(f"My name is {name}.")

Output
My name is Ele.

This new formatting syntax is very powerful and easy. You can also insert arbitrary Python expressions and you can even do arithmetic operations in it.

Arithmetic operations using F-strings

In this code, the f-string f” He said his age is {2 * (a + b)}.” is used to interpolate the result of the expression 2 * (a + b) into the string.

Python
a = 5
b = 10
print(f"He said his age is {2 * (a + b)}.")

Output
He said his age is 30.

We can also use lambda expressions in f-string formatting.

Lambda Expressions using F-strings

In this code, an anonymous lambda function is defined using lambda x: x*2. This lambda function takes an argument x and returns its double.

Python
print(f"He said his age is {(lambda x: x*2)(3)}")

Output
He said his age is 6

Float precision in the f-String Method

In this code, f-string formatting is used to interpolate the value of the num variable into the string.

Syntax: {value:{width}.{precision}}
Python
num = 3.14159

print(f"The valueof pi is: {num:{1}.{5}}")

Output
The valueof pi is: 3.1416

Note: To know more about f-strings, refer to f-strings in Python

4. Python String Template Class

In the String module, Template Class allows us to create simplified syntax for output specification. The format uses placeholder names formed by $ with valid Python identifiers (alphanumeric characters and underscores). Surrounding the placeholder with braces allows it to be followed by more alphanumeric letters with no intervening spaces. Writing $$ creates a single escaped $:

Formatting String Python Using Template Class

This code imports the Template class from the string module. The Template class allows us to create a template string with placeholders that can be substituted with actual values. Here we are substituting the values n1 and n2 in place of n3 and n4 in the string n.

Python
from string import Template

n1 = 'Hello'
n2 = 'GeeksforGeeks'

n = Template('$n3 ! This is $n4.')

# and pass the parameters into the
# template string.
print(n.substitute(n3=n1, n4=n2))

Output
Hello ! This is GeeksforGeeks.

Note: To know more about the String Template class, refer to String Template Class in Python

5. How to Format String using center() Method

The center() method is a built-in method in Python’s str class that returns a new string that is centered within a string of a specified width. 

Formatting string using center() method

This code returns a new string padded with spaces on the left and right sides.

Python
string = "GeeksForGeeks!"
width = 30

centered_string = string.center(width)

print(centered_string)

Output
        GeeksForGeeks!        

Python Format String: % vs. .format vs. f-string literal

f-strings are faster and better than both %-formatting and str.format(). f-strings expressions are evaluated at runtime, and we can also embed expressions inside f-string, using a very simple and easy syntax.

The expressions inside the braces are evaluated in runtime and then put together with the string part of the f-string and then the final string is returned.

Note: Use Template String if the string is a user-supplied string Else  Use f-Strings if you are on Python 3.6+, and. format() method if you are not.

We have covered all 5 ways of string formatting in Python. There are many use cases and examples for each method. We also compared these methods to find which one is most efficient to use in real-life projects.

Similar Reads:

Python String Formatting – How to format String? – FAQs

How Do You Format Strings in Python?

String formatting in Python can be achieved in several ways, each providing different benefits depending on the use case:

  1. Percent (%) Formatting: An older method that uses format specifiers like %s for strings and %d for integers.
  2. str.format() Method: Introduced in Python 2.6, this method uses curly braces {} as placeholders within the string and can specify more detailed formatting options.
  3. F-Strings (Literal String Interpolation): Introduced in Python 3.6, f-strings allow embedding expressions inside string literals, prefixed with f, providing a concise and readable way to include the results of expressions within strings.

What is %s and %d in Python?

In Python’s percent (%) formatting, %s and %d are format specifiers used to embed strings and integers into a format string, respectively.

  • %s is used for strings.
  • %d is used for integers.

Example:

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

What Does Mean in Python?

The {:d} format specifier in Python’s str.format() method is used to specify that the corresponding argument should be formatted as an integer (d stands for decimal).

Example:

number = 42
formatted_string = "The number is {:d}".format(number)
print(formatted_string) # Output: The number is 42

How to Use += in Python?

The += operator in Python is used to add a right-hand operand to a left-hand operand and assign the result back to the left-hand operand. It works with numerical values, strings, lists, and other data types that support addition operations.

Example with numbers:

x = 5
x += 3 # Equivalent to x = x + 3
print(x) # Output: 8

Example with strings:

s = "hello"
s += " world"
print(s) # Output: hello world

What is \t in Python?

In Python, \t represents a tab character. It is used in strings to add horizontal spacing. It is often used to make output more readable or to format it in a specific way.

Example:

print("Name:\tAlice\nAge:\t30")

Output:

Name:   Alice
Age: 30

This tab character adds a tab’s width of space in the output, which is typically equivalent to 4 or 8 spaces but can vary depending on the environment or settings used to display the text



Previous Article
Next Article

Similar Reads

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
Python Modulo String Formatting
In Python, a string of required formatting can be achieved by different methods. Some of them are; 1) Using % 2) Using {} 3) Using Template Strings In this article the formatting using % is discussed. The formatting using % is similar to that of 'printf' in C programming language. %d - integer %f - float %s - string %x - hexadecimal %o - octal The
2 min read
JSON Formatting in Python
JSON (JavaScript Object Notation) is a popular data format that is used for exchanging data between applications. It is a lightweight format that is easy for humans to read and write, and easy for machines to parse and generate. Python Format JSON Javascript Object Notation abbreviated as JSON is a lightweight data interchange format. It encodes Py
3 min read
Python code formatting using Black
Writing well-formatted code is very important, small programs are easy to understand but as programs get complex they get harder and harder to understand. At some point, you can’t even understand the code written by you. To avoid this, it is needed to write code in a readable format. Here Black comes into play, Black ensures code quality. What is B
3 min read
Formatting Axes in Python-Matplotlib
Matplotlib is a python library for creating static, animated and interactive data visualizations. Note: For more information, refer to Introduction to Matplotlib What is Axes? This is what you think of as 'plot'. It is the region of the image that contains the data space. The Axes contains two or three-axis(in case of 3D) objects which take care of
4 min read
Paragraph Formatting In Python .docx Module
Prerequisite: Working with .docx module Word documents contain formatted text wrapped within three object levels. The Lowest level- run objects, middle level- paragraph objects, and highest level- document object. So, we cannot work with these documents using normal text editors. But, we can manipulate these word documents in python using the pytho
9 min read
Hover Text and Formatting in Python-Plotly
Prerequisites: Python Plotly In this article, we will explore how to Hover Text and Formatting in Python. It is a useful approach to Hover Text and Formatting as it allows to reveal a large amount of data about complex information. One of the most deceptively-powerful features of data visualization is the ability for a viewer to quickly analyze a s
2 min read
Formatting Dates in Python
In different regions of the world, different types of date formats are used and for that reason usually, programming languages provide a number of date formats for the developed to deal with. In Python, it is dealt with by using a liberty called DateTime. It consists of classes and methods that can be used to work with data and time values. Require
5 min read
Python DateTime Formatting with Pendulum
Effective date and time management is essential in many applications. Compared to the default datetime module, Pendulum is a Python library that offers a more user-friendly and intuitive interface for manipulating dates. In this article, we will learn about datetime formatting with Pendulum in Python. Python DateTime Formatting with PendulumBelow,
3 min read
Python | Output Formatting
In Python, there are several ways to present the output of a program. Data can be printed in a human-readable form, or written to a file for future use, or even in some other specified form. Users often want more control over the formatting of output than simply printing space-separated values. Output Formatting in PythonThere are several ways to f
7 min read
Formatting Cells using openpyxl in Python
When it comes to managing Excel files programmatically, Python offers a powerful tool in the form of the openpyxl library. This library not only allows us to read and write Excel documents but also provides extensive support for cell formatting. From fonts and colors to alignment and borders, openpyxl makes it easy to customize our Excel sheets to
4 min read
Formatting float column of Dataframe in Pandas
While presenting the data, showing the data in the required format is also a crucial part. Sometimes, the value is so big that we want to show only the desired part of this or we can say in some desired format. Let's see different methods of formatting integer columns and the data frame it in Pandas. Formatting float column of Dataframe in PandasHe
3 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
Python String format() Method
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
13 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
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
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
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
Article Tags :
Practice Tags :