Tutorials Tonight
Follow Us

String Formatting in Python


In this article, we are going to learn about string formatting in Python. We will look at multiple different ways to format strings in Python in detail with examples.

String formatting is a method of printing a string by inserting variable values in it.

There are multiple different ways to format a string in Python which we are going to look at in detail in this article.

    Table Of Contents

  1. Quick Learning
  2. String formatting using % Operator
  3. format() Method
  4. Format string using f-string
  5. String template class
  6. Conclusion

Quick Learning

Let's quickly look at some of the different ways to format a string in python.

If you want to learn in detail about string formatting, then proceed further in the article.

# String formatting in python
name = "John"
age = 25

# method 1
print("My name is " + name + " and I am " + str(age) + " years old.")
# method 2
print("My name is %s and I am %d years old" % (name, age))
# method 3
print("My name is {0} and I am {1} years old".format(name, age))
# method 4
print(f"My name is {name} and I am {age} years old")

Output:

My name is John and I am 25 years old.
string formatting in python

1. String formatting using % Operator

The % operator is the oldest method to format a string in Python. % is also known as the modulo operator.

This method was mainly used in older versions of Python, like Python 2.x. It is versatile, simple, and power full. It can also be used with the current version of Python.

Let's look at an example:

# format a string with % operator

print("My name is %s." % "John")
# My name is John.

%s is a placeholder for a string also known as a modulo specifier. It is used to format a string. If you have a background in a language like C, you will easily recognize it.

Let's look at the modulo specifier for other data types:

Modulo Specifiers

Just like %s for the string we also have other specifiers for other data types. Let's look at some examples:

Example 1: Formatting integers

Formatting string with integers using %d.

# %d for integer
age = 25

print("My age is %d years old." % age)

The above example will print:

My age is 25 years old.

Example 2: Formatting Multiple values

You can also format multiple values using the % (modulo) operator. Let's look at an example:

# multiple values format
age = 25
name = "John"

print("My name is %s and I am %d years old." % (name, age))

# another one
print("Hello %s. %d apples. %fkg of apples." % ("John", 10, 1.5))

The above example will print:

My name is John and I am 25 years old.
Hello John. 10 apples. 1.5kg of apples.

Example 3: Formatting floats

Formatting string with floats using %f.

# %f for float
pi = 3.14159265359

print("Pi is %f." % pi)

Output:

Pi is 3.14159265359.

The float numbers can also be rounded off to a certain number of decimal places using %f. To do this, we can use %.[number of decimal places]f.

# %.[number of decimal places]f for float
pi = 3.14159265359

print("Pi is %.2f." % pi)
print("Pi is %.4f." % pi)
print("Pi is %.6f." % pi)

Rounded off output:

Pi is 3.14.
Pi is 3.1416.
Pi is 3.141593.

Example 4: Formatting characters

Formatting string with a single character. We will use %c as a specifier.

# %c for character

print("My favorite character is %c" % 'S')

Output:

My favorite character is S.

Example 5: Formatting octal & hexadecimal

Formatting string with octal and hexadecimal. We will use %o and %x as specifiers. The passing arguments for both of these must be integers.

# %o for octal
num = 25
print("Octal value for %d is %o" % (num, num))

# %x for hexadecimal
num = 19
print("Hexadecimal value for %d is %x" % (num, num))

Output:

Octal value for 25 is 31.
Hexadecimal value for 19 is 13.

2. Using format() Method

The format() method is a powerful way to format a string. It was introduced in Python 3 and is used to format a string with multiple values.

format() function works by putting curly braces {} around the placeholders and passing the values as arguments to the function. The placeholders are replaced with the values passed as arguments to the function.

Syntax

The format function can be used in 3 different ways. As shown in the syntax below.

# place in order
"{} {} {}".format(value1, value2, value3)

# place by number
"{0} {1} {2}".format(value1, value2, value3)

# place by name
"{a} {b} {c}".format(a=value1, b=value2, c=value3)

Let's look at examples to understand in a better way.

Example 1

Using format() function to format string.

# format() function

print("My name is {}.".format("John"))
# output: My name is John.

Example 2

Formatting multiple values using format() function.

# multiple values format

print("My name is {} and I am {} years old.".format("John", 25))
# output: My name is John and I am 25 years old.

Example 3

Using number as a placeholder in format() function.

# number as placeholder

print("My name is {0} and I am {1} years old.".format("John", 25))
# output: My name is John and I am 25 years old.
# number as placeholder

print("{3} {2} {1} {0}".format("John", "Paul", "George", "Ringo"))
# output: Ringo George Paul John

Example 4

Using name as a placeholder in format() function.

# name as placeholder

print("My name is {name} and I am {age} years old.".format(name="John", age=25))
# output: My name is John and I am 25 years old.

Example 5

Using the same name multiple times in the format() function.

# same name multiple times

print("{greet} Peter. {greet} John".format(greet="Hello"))
# output: Hello Peter. Hello John.

3. Format String Using f-string

The f-string is a new feature in Python 3.6 and is used to format a string in Python.

This is more readable, easier to write, and looks more cleaner than other formatting methods.

This is known as f-string because it uses f as the first character in the string. After the f, we can put any expression that can be evaluated in the string within the curly braces {}.

# f-string
name = "John"

print(f"My name is {name}.")
# output: My name is John.

You can also use f-string to format multiple values.

# f-string multiple values
name = "John"
age = 25

print(f"My name is {name} and I am {age} years old.")
# output: My name is John and I am 25 years old.

Any valid expression can be used in the f-string.

# f-string expression

print(f"Sum of {1+2} and {3+4} is {1+2+3+4}.")
# output: Sum of 3 and 7 is 12.

Another example of using the expression in f-string.

# f-string expression

print(f"First 10 natural numbers are {list(range(1, 11))}.")
# output: First 10 natural numbers are [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].

4. String Template Class

In python String modulo has a Template class that is used to format a string.

The Template class creates a template object which supports $ substitution.

After creating the template object, the substitute() method is used to substitute the values in the template.

# string template class
from string import Template

# create template object
template = Template("My name is $name and I am $age years old.")

# substitute values
print(template.substitute(name="John", age=25))
# output: My name is John and I am 25 years old.

Conclusion

String formatting in Python can be performed in 4 different ways.

  1. Using %
  2. Using format() method
  3. Using f-string
  4. Using Template class