Table of contents
1.
Introduction
2.
Python String format() Method
3.
Python String format() Syntax
4.
String format() in Python Example
5.
How to Format Strings in Python:
5.1.
Using .Format() Method
5.2.
Understanding Python f-string
5.3.
Python String Template Class
5.3.1.
Create a template string
6.
Python Format String: % vs. .format vs. f-string literal
7.
How to Format String using center() Method
8.
Using a Single Formatter
8.1.
String format() with Multiple Placeholders
8.2.
String format() IndexError
9.
Formatting Strings Using Escape Sequences
10.
Formatters with Positional and Keyword Arguments
10.1.
1. Positional Arguments
10.2.
2. Keyword Arguments
11.
Type Specifying in Python
11.1.
Using %s – String Conversion via str() Prior to Formatting
11.2.
Using %c – Character Prior to Formatting
11.3.
Using %i Signed Decimal Integer and %d Signed Decimal Integer (Base-10) Prior to Formatting
11.4.
Another Useful Type Specifying
12.
Errors and Exceptions
13.
Convert Base-10 Decimal Integers to Floating-Point Numeric Constants
14.
Frequently Asked Questions
14.1.
What is the use of the format() method in Python?
14.2.
How do I handle multiple placeholders in a string?
14.3.
What is the difference between positional and keyword arguments in string formatting?
15.
Conclusion
Last Updated: Dec 30, 2024
Medium

Python String format()

Author Rahul Singh
0 upvote

Introduction

In Python, strings are essential, and formatting them properly is a skill every programmer should master. The format() method in Python allows you to create strings with dynamic content, making it easy to insert variables into text. 

Python String format()

In this article, we will discuss how to use the format() method effectively, including examples of formatting strings with placeholders, handling multiple values, and common errors. 

Python String format() Method

The format() method is a powerful and flexible way to insert values into strings in Python. It allows you to format string templates by adding values, variables, or even expressions into a string at specific positions. This method helps keep your code clean and readable, especially when dealing with complex strings.

For example, you might want to create a greeting message that dynamically inserts a person’s name. With the format() method, this becomes simple and straightforward.

Python String format() Syntax

The basic syntax for the format() method looks like this:

"string {} {}".format(value1, value2)


Here, {} are placeholders in the string, where the values will be inserted. The format() method takes arguments (like value1 and value2), which replace the placeholders in the string.

String format() in Python Example

Let’s see how the format() method works in action:

name = "Alice"
age = 20
message = "My name is {} and I am {} years old.".format(name, age)
print(message)
You can also try this code with Online Python Compiler
Run Code


Output:

My name is Alice and I am 20 years old.


In this example, the format() method inserts the values of name and age into the string, replacing the placeholders {}.

How to Format Strings in Python:

Python provides several ways to format strings, allowing developers to create dynamic output by inserting values into predefined placeholders. String formatting is useful when you need to combine static text with variables or expressions to generate readable & informative messages.

For example: 

name = "Sinki"
age = 25
print("My name is {} & I am {} years old.".format(name, age))
You can also try this code with Online Python Compiler
Run Code


Output:

My name is Sinki & I am 25 years old.


In this example, the placeholders {} are used to mark the positions where the values of name & age should be inserted. The .format() method is then called on the string, passing the variables as arguments in the order they should appear.

String formatting makes your code more readable & maintainable by separating the structure of the output from the actual values. It allows you to create templates that can be reused with different data.

Python offers several string formatting techniques, like:

1. Using the .format() method

2. Using f-strings (formatted string literals)

3. Using the string Template class

Using .Format() Method

The .format() method is a powerful way to format strings in Python. It allows you to insert values into a string by placing placeholders {} where you want the values to appear. Let’s see how you can use the .format() method:

1: Basic usage

print("Hello, {}!".format("Sinki"))
You can also try this code with Online Python Compiler
Run Code


Output: 

Hello, Sinki!


2: Multiple values

name = "Dev"
age = 30
print("My name is {} & I am {} years old.".format(name, age))
You can also try this code with Online Python Compiler
Run Code


Output:

 My name is Dev & I am 30 years old.


3: Indexed placeholders

print("I have a {0}, a {1}, & a {2}.".format("cat", "dog", "bird"))
You can also try this code with Online Python Compiler
Run Code


Output:

 I have a cat, a dog, & a bird.


4: Named placeholders

print("I have a {pet1}, a {pet2}, & a {pet3}.".format(pet1="cat", pet2="dog", pet3="bird"))
You can also try this code with Online Python Compiler
Run Code


Output: 

I have a cat, a dog, & a bird.
You can also try this code with Online Python Compiler
Run Code


The .format() method provides a lot of flexibility in terms of specifying the placeholders. You can use empty placeholders {}, indexed placeholders {0}, {1}, etc., or named placeholders {name}.

When using indexed placeholders, the values are inserted based on their position in the .format() method. With named placeholders, you can provide the values as keyword arguments, making the code more readable.

You can also control the formatting of the inserted values using format specifiers. For example:

1: Formatting numbers

print("The value of pi is approximately {:.2f}".format(3.14159))
You can also try this code with Online Python Compiler
Run Code


Output: 

The value of pi is approximately 3.14
You can also try this code with Online Python Compiler
Run Code


In this example, {:.2f} specifies that the value should be formatted as a floating-point number with two decimal places.

Understanding Python f-string

Python f-strings, introduced in Python 3.6, provide a concise & readable way to embed expressions inside string literals. f-strings are prefixed with the letter 'f' & allow you to include variables or expressions directly within the string. Let’s see how you can use f-strings:

name = "Sinki"
age = 25
print(f"My name is {name} & I am {age} years old.")
You can also try this code with Online Python Compiler
Run Code


Output: 

My name is Sinki & I am 25 years old.


In this example, the variables name & age are directly inserted into the string using the {} placeholders. The 'f' prefix before the string indicates that it is an f-string.

One advantage of f-strings is that you can include any valid Python expression inside the placeholders. For example:

value = 10
print(f"The square of {value} is {value ** 2}")
You can also try this code with Online Python Compiler
Run Code


Output: 

The square of 10 is 100

Here, the expression value ** 2 is evaluated & the result is inserted into the string.

f-strings also support format specifiers, similar to the .format() method. You can add formatting instructions after a colon : within the placeholders. For example:

pi = 3.14159
print(f"The value of pi is approximately {pi:.2f}")
You can also try this code with Online Python Compiler
Run Code


Output: 

The value of pi is approximately 3.14


In this case, {pi:.2f} specifies that the value of pi should be formatted as a floating-point number with two decimal places.

f-strings offer a more concise & readable syntax compared to the .format() method, especially when dealing with simple string formatting. They allow you to embed expressions directly within the string, making the code more intuitive & easier to understand.

Note: f-strings are a powerful tool for creating formatted strings in Python, & they are widely used in modern Python development.

Python String Template Class

Python's string Template class provides another way to create formatted strings. It allows you to define a string template with placeholders & substitute values into those placeholders later. Let’s discuss how you can use the string Template class:

from string import Template

Create a template string

template = Template("My name is $name & I am $age years old.")
Substitute values into the template
output = template.substitute(name="Dev", age=30)
print(output)
You can also try this code with Online Python Compiler
Run Code


Output: 

My name is Dev & I am 30 years old.


In this example, we first import the Template class from the string module. We then create a template string using the Template constructor, with placeholders prefixed with the $ symbol.

To substitute values into the template, we call the substitute() method on the template object, passing the values as keyword arguments. The placeholders in the template are replaced with the corresponding values.

The string Template class provides a safer way to format strings compared to using regular string formatting with % or .format(). It avoids potential security risks associated with directly embedding user input into string formatting expressions.

However, the string Template class has some limitations compared to other formatting methods, like:

1. It does not support complex expressions inside the placeholders, only simple variable substitution.

2. It does not provide advanced formatting options like alignment, padding, or type-specific formatting.

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

Python provides multiple ways to format strings, including the % operator, the .format() method, and f-string literals. Let's compare these methods and discuss their advantages and disadvantages.

1. % operator:

  • The % operator is the oldest way to format strings in Python.
     
  • It uses % as a placeholder for values and requires a tuple of values to be provided.
     
  • Example: `"Hello, %s!" % name`
     
  • Advantages:
    - It is widely supported across different Python versions.
     
  • Disadvantages:
    - It can become difficult to read and maintain when dealing with many placeholders.

    - It does not support named placeholders.

2. .format() method:

  • The .format() method was introduced in Python 2.6 and provides a more flexible way to format strings.
     
  • It uses {} as placeholders and allows for positional or named arguments.
     
  • Example: `"Hello, {}!".format(name)` or `"Hello, {name}!".format(name=name)`
     
  • Advantages:
    - It provides more control over the formatting, such as specifying alignment, padding, and type-specific formatting.

    - It supports named placeholders, making the code more readable.
     
  • Disadvantages:
    - It can be verbose when dealing with simple string formatting.

3. f-string literals:

  • f-string literals, introduced in Python 3.6, provide a concise and readable way to embed expressions inside string literals.
     
  • They are prefixed with the letter 'f' and allow variables or expressions to be directly included within the string.
     
  • Example: `f"Hello, {name}!"`
     
  • Advantages:
    - They offer a clean and intuitive syntax for string formatting.

    - They support embedding expressions directly within the string.
     
  • Disadvantages:
    - They are only available in Python 3.6 and above.

In general, f-string literals are the recommended choice for string formatting in modern Python code due to their readability and conciseness. However, the .format() method is still widely used and provides more flexibility and compatibility with older Python versions. The % operator, while still supported, is generally considered less readable and is less commonly used in new code.

How to Format String using center() Method

The center() method is a built-in string method in Python that allows you to center-align a string within a specified width. It pads the string with a given character (default is space) on both sides to achieve the desired width. Let’s see how you can use the center() method:

text = "Hello"
centered_text = text.center(10)
print(centered_text)
You can also try this code with Online Python Compiler
Run Code


Output:  

 Hello   


In this example, the center() method is called on the string "Hello" with a width of 10. The resulting centered_text string is padded with spaces on both sides to reach the specified width.

You can also provide a fill character as the second argument to the center() method. For example:

text = "Python"
centered_text = text.center(12, "*")
print(centered_text)
You can also try this code with Online Python Compiler
Run Code


Output:

 Python


Here, the string "Python" is centered within a width of 12 characters, & the asterisk (*) is used as the fill character instead of spaces.

The center() method is useful when you want to display text in a visually appealing & centered format. It can be helpful in creating formatted output, such as tables or reports, where consistent alignment is desired.

It's important to note that the center() method does not modify the original string; instead, it returns a new string with the centered alignment. If the specified width is less than the length of the string, the original string is returned unchanged.

Using a Single Formatter

If you only need to insert one value into a string, you can still use the format() method with a single placeholder:

greeting = "Hello, {}!".format("World")
print(greeting)
You can also try this code with Online Python Compiler
Run Code


Output:

Hello, World!

String format() with Multiple Placeholders

When you need to insert multiple values into the string, use multiple {} placeholders. The order in which the values are inserted follows the order of the arguments passed to format().

name = "John"
age = 25
city = "New York"
info = "Name: {}, Age: {}, City: {}".format(name, age, city)
print(info)
You can also try this code with Online Python Compiler
Run Code


Output:

Name: John, Age: 25, City: New York

String format() IndexError

An IndexError occurs when the number of placeholders does not match the number of values provided. Here’s an example of what can go wrong:

# Incorrect number of values
name = "Sarah"
greeting = "Hello {}, you are {} years old.".format(name)
print(greeting)
You can also try this code with Online Python Compiler
Run Code


Output:

IndexError: tuple index out of range


This error happens because the second placeholder expects a second argument, but only one is provided.

Formatting Strings Using Escape Sequences

Escape sequences are useful when you need special characters in a string, like newlines, tabs, or quotes. The format() method can handle these as well.

escaped_string = "This is a quote: \"Python is great!\""
print(escaped_string)
You can also try this code with Online Python Compiler
Run Code


Output:

This is a quote: "Python is great!"


You can also use escape sequences like \n (newline) or \t (tab) inside formatted strings.

Formatters with Positional and Keyword Arguments

You can use both positional and keyword arguments in the format() method to make your code more readable.

1. Positional Arguments

message = "Hello {0}, you are {1} years old.".format("Alice", 30)
print(message)
You can also try this code with Online Python Compiler
Run Code


Output:

Hello Alice, you are 30 years old.

2. Keyword Arguments

message = "Hello {name}, you are {age} years old.".format(name="Bob", age=40)
print(message)
You can also try this code with Online Python Compiler
Run Code


Output:

Hello Bob, you are 40 years old.


Positional arguments use numbers inside {}, while keyword arguments use the variable names.

Type Specifying in Python

Python’s format() method also allows you to specify how values are displayed by defining the type of the argument. You can format the value as integers, strings, floating-point numbers, and more.

Here’s an example using type specifying:

number = 45.6789
formatted_string = "The number is {:.2f}".format(number)
print(formatted_string)
You can also try this code with Online Python Compiler
Run Code


Output:

The number is 45.68

Using %s – String Conversion via str() Prior to Formatting

If you want to explicitly convert a value to a string before inserting it into a formatted string, you can use %s.

num = 100
formatted_string = "The number is %s" % str(num)
print(formatted_string)
You can also try this code with Online Python Compiler
Run Code


Output:

The number is 100

Using %c – Character Prior to Formatting

The %c operator allows you to insert characters into a string.

char = 'A'
formatted_string = "The character is %c" % char
print(formatted_string)
You can also try this code with Online Python Compiler
Run Code


Output:

The character is A

Using %i Signed Decimal Integer and %d Signed Decimal Integer (Base-10) Prior to Formatting

The %i and %d operators are used to format signed decimal integers.

num = 42
formatted_string = "The number is %d" % num
print(formatted_string)
You can also try this code with Online Python Compiler
Run Code


Output:

The number is 42

Another Useful Type Specifying

You can also format other types like hexadecimal or percentage values.

num = 255
formatted_string = "The number in hex is {:x}".format(num)
print(formatted_string)
You can also try this code with Online Python Compiler
Run Code


Output:

The number in hex is ff


This converts the number into its hexadecimal form.

Errors and Exceptions

When using the format() method, you might run into some common errors such as IndexError or ValueError. Make sure to pass the correct number of arguments and that placeholders match the expected values.

Here’s an example of catching an error:

try:
    message = "Hello {}, you are {}.".format("Alice")
except IndexError as e:
    print("Error:", e)
You can also try this code with Online Python Compiler
Run Code


Output:

Error: tuple index out of range

Convert Base-10 Decimal Integers to Floating-Point Numeric Constants

You can also convert base-10 integers into floating-point numbers using the format() method.

number = 123
formatted_string = "The float is {:.2f}".format(float(number))
print(formatted_string)
You can also try this code with Online Python Compiler
Run Code


Output:

The float is 123.00

Frequently Asked Questions

What is the use of the format() method in Python?

The format() method is used to insert values into strings at specific places, making it easier to build dynamic strings with variables and expressions.

How do I handle multiple placeholders in a string?

You can use multiple curly braces {} to insert different values at specific locations in the string. Pass the values to the format() method in the same order.

What is the difference between positional and keyword arguments in string formatting?

Positional arguments use index numbers (like {0}, {1}), while keyword arguments use variable names (like {name}, {age}) for better readability.

Conclusion

In this article, we discussed the format() method in Python, a versatile tool for string formatting. You learned how to use placeholders, handle multiple arguments, and apply various formatting techniques like type specification and error handling. By mastering these concepts, you’ll be able to build dynamic and readable strings, which are essential in many programming tasks.

You can also check out our other blogs on Code360.

Live masterclass