TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: Python String Formatting Methods
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile Concepts Simplified
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Python BasicPython Tutorials

Python String Formatting Methods

Last updated: Nov 23, 2023 11:23 am
By Meenakshi Agarwal
Share
4 Min Read
Format or percentage for string formatting in Python
SHARE

String formatting is the process of constructing a string by inserting values into specific locations. With this purpose in mind, we’ll explore different methods in this quick tutorial. You’ll get to know which method from the League of format() function, percentage (%), f-strings, center(), or template class to use in Python to format strings.

Contents
1. Using Percentage (%) to Format StringsAdvantages of % Formatting:Note2. Using Format() FunctionHow to use str.format()Advantages of str.format()3. Python F-string for String FormattingAdvantages of F-Strings:4. string.Template ClassAdvantages of string.Template5. str.center() MethodHow to use str.center()Advantages of str.center()Comparison of Python String Formatting Methods

Python String Formatting Different Methods

In this tutorial, we will explore five common string formatting methods: f-strings, the str.format() method, old-style % formatting, the string.Template class, and the str.center() method. We will also provide a comparison table at the end to help you choose the most suitable method for your specific needs.

Format or percentage for string formatting in Python

Let’s start with the % method and then move on to the others.

1. Using Percentage (%) to Format Strings

The % operator is a legacy Python method for string formatting. It works by replacing placeholders in a string with values from a tuple.

If you just have to do some basic string changes, then the operator ‘%’ is useful. It will evoke similarities with the C programming language. Here is a basic example to illustrate its usage.

name = "Duckworth-Lewis-Stern"
age = 1997

formatted_string = "The name method %s was introduced in %d." % (name, age)
print(formatted_string)

# The Duckworth-Lewis-Stern method was introduced in 1997.

Please note that you need to postfix '%' with a type-specific char to indicate the type of data to print. It signifies whether to substitute a number or a string in the formatted message.

The following table shows some of the most common conversion specifiers. You can use these commonly with the ‘%’.

Conversion specifierDescription
sString
dInteger
fFloating-point number

In case you don’t specify the integer type value against the ‘%d’, Python will throw the TypeError. The limitation of such a method is that it restricts the type of parameter input.

Advantages of % Formatting:

  • Suitable for developers coming from a C or C++ background.
  • Can be used in Python 2 and Python 3.

Note

Do you want to know how to use the XOR operator in Python? It is a powerful tool for crypto operations such as encryption, generating checksum, and hashing functions.

2. Using Format() Function

The str.format() method provides a flexible way to format strings by substituting placeholders with values. This method is available in Python 2 and Python 3, making it a good choice for code that needs to be compatible with both versions.

How to use str.format()

In a string, you can define placeholders using curly braces {}. Then, call the format() method on the string and provide the values to be inserted as arguments to the format() method.

city = "New York"
population = 8_400_000
average_income = 72_000

formatted_info = "Welcome to {}, where {} people thrive with an average income of ${} per year.".format(city, population, average_income)
print(formatted_info)

Once you run the above code, it prints the following:

Welcome to New York, where 8400000 people thrive with an average income of $72000 per year.

In this example, we’re formatting a string to display information about a city, its population, and the average income using the str.format() method.

Advantages of str.format()

  • Provides flexibility in specifying placeholders.
  • Compatible with both Python 2 and Python 3.

3. Python F-string for String Formatting

f-strings are the newest method of string formatting in Python. They first surfaced in Python 3.6 and became the most concise and readable way to format strings.

f-strings work by embedding expressions in curly braces ({}), and the expressions are evaluated at runtime and inserted into the string. For example, the following code clarifies how simple it is to use f-string to format strings in Python.

name = "Steve"
age = 21
profession = "Software Engineer"
print(f"{name} is {age} years old, and he is a {profession}.")

Furthermore, f-strings can help you format multiple values, and even specify the order of insertion. For example, the following code will print the same string as the previous example:

name = "Steve"
age = 21
profession = "Software Engineer"
print(f"{0} is {1} years old, and he is a {2}.")

Advantages of F-Strings:

  • Readable and concise syntax.
  • Supports complex expressions within curly braces.
  • Available in Python 3.6 and later.

4. string.Template Class

The string.Template is available in the Python template module. It provides a safe and extensible way to perform string substitutions. For instance, it can be useful for creating dynamic strings that reoccur frequently, such as generating HTML pages or emails.

In order to use the Template class, you first need to create a template string. Simultaneously, you have to specify the placeholders using dollar signs ($). For example, the following template string contains two placeholders:

from string import Template

name = "Ageless"
age = 'constant'
template = Template("I am $name and my immortality is a $age.")
formatted_string = template.substitute(name=name, age=age)
print(formatted_string)

After running the above code, you will get the following output.

I am Ageless and my immortality is a constant.

Advantages of string.Template

  • Safe against common security issues, such as code injection.
  • Simple and easy to use for basic string substitutions.

5. str.center() Method

The method str.center() is used for the purpose of center-aligning a string within a given width. While it’s not a traditional string formatting method, it’s helpful when you need to align text in a specific way.

How to use str.center()

Call the center() method on a string, passing the desired width as an argument. The method will pad the string with spaces to center it within the specified width.

For example, the following code will center the string “Hello, world!” within a width of 20:

text = "Hello, world!"
print(text.center(20))

The above code will print the input text in the center of the given width.

   Hello, world!    

Advantages of str.center()

  • Useful for aligning text in specific formatting scenarios.
  • Simplicity and ease of use.

Comparison of Python String Formatting Methods

Now, let’s compare these string formatting methods to help you choose the most suitable one for your needs:

MethodDescriptionAdvantagesDisadvantages
% operatorThe oldest method of string formatting in Python.Simple and straightforward.Not very powerful or flexible.
.format() methodA newer method of string formatting in Python.More powerful and flexible than the % operator.Can be complex.
f-stringsThe newest method of string formatting in Python.Most concise and readable way to format strings.Not supported in older versions of Python.
Template classAllows you to create template strings with placeholders that can be substituted with actual values.Useful for creating dynamic strings that are used repeatedly.Can be complex.
Center methodCenters a string within a given width.Useful for formatting strings for display.Only formats a single string.

Which Method Should You Use?

The best method to use for string formatting depends on your specific needs. If you need to format a simple string, then the % operator or format() method is a good option. If you need to format a string that is used repeatedly, then the Template class is a good option. However, in order to center a string within a given width, the center() method is a good option.

In summary, if you are using Python 3.6 or higher, then f-strings are the best option for most cases. They are the most concise and readable way to format strings.

You Might Also Like

How to Connect to PostgreSQL in Python

Generate Random IP Address (IPv4/IPv6) in Python

Python Remove Elements from a List

Selenium Python Extent Report Guide

10 Python Tricky Coding Exercises

Meenakshi Agarwal Avatar
By Meenakshi Agarwal
Follow:
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large MNCs, I gained extensive experience in programming, coding, software development, testing, and automation. Now, I share my knowledge through tutorials, quizzes, and interview questions on Python, Java, Selenium, SQL, and C# on my blog, TechBeamers.com.
Previous Article types of inheritance in java Java Inheritance Types
Next Article Various Python for loop example Python For Loop Examples

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x
x