Close
Close

Python String Formatting


We have already learned about strings. In this section, we will go through some formatting techniques to make our string more presentable.

Look at the following example.

# taking input from user
amount = int(input("Enter the amount"))

# displaying output
print("Amount is $", amount)
Output
Enter the amount45
Amount is $ 45

In the first statement, we are taking an input from the user and assigning it to the variable amount. In the second statement, we are printing a string. What if we don’t want that space between $ and 45 in the output?

This is where the need for formatting a string arises. There can be other such scenarios where we will need some formatting to obtain the desired string.

So, let’s look at the different ways we can format strings.

Python Modulo Operator (%)


Using % is the old way of formatting

We use argument specifiers like %s, %d, etc., in strings which are then replaced by some value. Look at the following example.

some_string = "Hello World"
formatted_string = "The computer says %s" % some_string

# displaying output
print(formatted_string)
Output
The computer says Hello World

Here, the argument specifier %s in the string "The computer says %s" got replaced by the value of the variable some_string, thus making our formatted string as "The computer says Hello World". Note that we use the argument specifier %s when we want to replace it by a string.

As we used %s for string, we can use %d for integer. Let’s look at some argument specifiers before looking at more examples.

As stated above, using modulo operator (%) is an old way. There are many simpler ways explained later in this chapter.
Argument Specifier Gets replaced by
%s String
%d Integer
%f Floating point number
%.f Floating point number with specified number of digits after decimal
%c Character
%x Hex representation of Integers (lowercase)
%X Hex representation of Integers (uppercase)
print("%s" % "Python programming")
Output
Python programming

In this example, %s is an argument specifier which got replaced by the string "Python programming".

Let’s rewrite the code of the first example of this chapter solving the problem we were facing.

# taking input from user
amount = int(input("Enter the amount"))

# displaying output
print("Amount is $%d" % amount)
Output
Enter the amount45
Amount is $45

Now the extra space between $ and 45 is no more. We used %d as the specifier because amount is an integer.

If multiple values have to be printed in a single print() function, then  for each value we need to give a separate argument specifier in the string which is to be printed as the output.

print("My name is %s %s and my age is %d" % ("John", "Doe", 45))
Output
My name is John Doe and my age is 45

Notice that the values are enclosed within parentheses ( ) and separated by commas. The order of writing the values is also the same as that of the argument specifiers in the string which is printed. Therefore, the first %s got replaced by “John”, second %s by “Doe” and %d by 45.

modulo string operator in Python

This formatting method can also be used to print a specified number of digits after the decimal of a floating point value.

num = 2.333333333
print("%.2f" % num)
Output
2.33

Python String format() method


Strings can also be formatted using the str.format() function. We use { } for a placeholder in the string. The placeholder { } in the string is replaced by the value passed to the format() function. This will become clear from an example.

print("Hello {}".format("John"))
Output
Hello John

In this example, format() function is applied to the “Hello {}” string. The placeholder { } in the string is replaced by the value “John” passed to the format() function, thus making the string as “Hello John”.

Let’s again rewrite the first example of this chapter using this method.

# taking input from user
amount = int(input("Enter the amount"))

# displaying output
print("Amount is ${}".format(amount))
Output
Enter the amount45
Amount is $45

Passing Multiple Arguments to Python format()


If multiple values need to be substituted in a string, then we pass the values separated by commas to the format() function and add the corresponding placeholders { } in the output string. This will become more clear from the following example.

print("My name is {} {} and my age is {}".format("John", "Doe", 45))
Output
My name is John Doe and my age is 45

The first placeholder got replaced by the first value passed to the format() function. Similarly, the second and third placeholders got replaced by the second and third values passed respectively.

Passing Positional Arguments to Python format()


In case of multiple values being substituted in a string, to change the order in which the values appear in the string, give the index numbers of the values in the placeholders { }. The index of the values start from 0.

print("My name is {1} {2} and my age is {0}".format(45, "John", "Doe"))
Output
My name is John Doe and my age is 45

Based on the order of the values passed to the format() function, the index of 45 is 0, “John” is 1 and “Doe” is 2. Therefore, the placeholders {0}, {1} and {2} got replaced by 45, “John” and “Doe” respectively.

Index starts from 0 and not 1.

Passing Keyword Arguments to Python format()


Instead of identifying values by their indices, we can also use some names to identify values in placeholders.

print("My name is {fname} {lname} and my age is {age}".format(age = 45, fname = "John", lname = "Doe"))
Output
My name is John Doe and my age is 45

The names age, fname and lname are assigned the values 45, “John” and “Doe” respectively. Therefore, the placeholders {age}, {fname} and {lname} got replaced by 45, “John” and “Doe” respectively.

Hybrid of Positional and Keyword Arguments to Python format()


When using a mix of positional and keyword arguments, we need to make sure that the keyword arguments are always passed at the end.

print("My name is {fname} {lname} and my age is {0}".format(45, fname = "John", lname = "Doe"))
Output
My name is John Doe and my age is 45

Here, 45 is a positional argument and fname = "John" and lname = "Doe" are keyword arguments. Notice that the keyword arguments are written after the positional argument.

Let’s see what would happen if we write a keyword argument before a positional argument.

print("My name is {fname} {lname} and my age is {0}".format(fname = "John", 45, lname = "Doe"))
Output
File "<stdin>", line 1
SyntaxError: positional argument follows keyword argument

As expected, we got an error.

Using Argument Specifiers with Python format()


Using format() also, we can use the same argument specifiers shown in the previous modulo operator (%) method. The argument specifier is written inside the placeholder { } following a colon : instead of %.

Look at the following examples.

print("Hello {:s}".format("John"))
Output
Hello John
print("My name is {1:s} {2:s} and my age is {0:d}".format(45, "John", "Doe"))
Output
My name is John Doe and my age is 45

You must have understood these examples. Notice that %s and %d in the previous formatting method have been replaced by :s and :d here. However, using the argument specifiers :s and :d was not necessary in these examples.

We can use argument specifiers to round off a floating point number to a specified number of digits after decimal as shown below.

num = 2.333333333
print("This number is rounded off to 2 digits after decimal - {:.2f}".format(num))
Output
This number is rounded off to 2 digits after decimal - 2.33

Again, %.2f has been replaced by :.2f in this example.

Python Formatted String Literal (f-String)


F-strings were introduced in Python version 3.6. These are quite similar to strings in Python.

Syntax of f-string


f'str'
Or
f"str"
Or
f'''str'''

So, f-string for the string "Hello John" will be f"Hello John".

print("Hello John")
print(f"Hello John")
Output
Hello John
Hello John

As you can see, the f-string displayed the same result as the other string.

F-strings can also contain braces { }. The value, variable or expression written within the braces { } gets evaluated and replaces the braces in the string.

name = "John"
print(f"Hello {name}")
Output
Hello John

Here, the value “John” of the variable name replaced the braces in the f-string.

Let’s solve the problem we were facing in the first example of this chapter using this method.

# taking input from user
amount = int(input("Enter the amount"))

# displaying output
print(f"Amount is ${amount}")
Output
Enter the amount45
Amount is $45

Look at some more examples.

fname, lname, age = "John", "Doe", 45
print(f"My name is {fname} {lname} and my age is {age}")
Output
My name is John Doe and my age is 45
num1, num2 = 1, 2
print(f"Sum of {num1} and {num2} is {num1 + num2}")
Output
Sum of 1 and 2 is 3
Behind every successful person lies a pack of haters.
- Eminem


Download Our App.
BlogsDope App
Get it on Google Play
Ask Yours
Post Yours
Doubt? Ask question