Python String Formatting


Python String Formatting

String formatting comes into the picture when we want to insert items into the string. For example:

In [1]:
first_name = "Steve"
id = 5
print(first_name +", your ID is " + str(id) + ".")
Steve, your ID is 5.

The above approach is inefficient if we insert too many variables into the string. Especially, in the case of integers and floats, they all have to be converted into strings. So, we have a few other methods.

We can perform string formatting using any of these:

  1. String Formatting Operator(%)
  2. .format() method
  3. f-string
  4. Template Strings

Python String Formatting

String Formatting Operator(%)

The symbol % is known as the string formatting operator. This symbol is used with other characters to insert various types of values. For example, we can use %s for string and %f for floating-point numbers.

%s is used to insert a value as a string.

In [1]:
print("How are you %s." %'Steve')
How are you Steve.
In [2]:
first_name = "Steve"
last_name = "Jobs"
print("How are you %s %s." %(first_name, last_name))
How are you Steve Jobs.

%d is used to insert a value as an integer.

In [3]:
bill = 54.98
print("Your bil is %s" %bill)
print("Your bil is %d" %bill)
Your bil is 54.98
Your bil is 54

% for width and alignment

%f is used to insert a value as a float.

In [1]:
bill = 54.98
print("Your bill is %f" %bill)
Your bill is 54.980000

Total 12 numbers and 4 after decimal.

In [2]:
bill = 54.98
print("Your bill is %12.4f" %bill)
Your bill is      54.9800

Total 12 numbers and 0 after decimal.

In [3]:
bill = 54.98
print("Your bill is %12.0f" %bill)
Your bill is           55

format() method

The format() method improves the string formatting operator. The format method is called after the string, and the items are passed as parameters to the format method. Curly brackets are used as the placeholders inside the string.

Curly bracket as placeholder.

In [1]:
print("Hello {}, {} was calling you and {}.".format("Steve","Bill", "Tim"))
Hello Steve, Bill was calling you and Tim.

We can use index position of arguments also, which starts from 0.

In [2]:
print("Hello {1}, {0} was calling you and {2}.".format("Steve","Bill", "Tim"))
Hello Bill, Steve was calling you and Tim.

We can assign keys to arguments also, like s, b and t assigned below. This key is used in placeholder.

In [3]:
print("Hello {t}, {b} was calling you and {s}.".format(s = "Steve",b = "Bill", t = "Tim"))
Hello Tim, Bill was calling you and Steve.

format() for width and alignment

Simply printing float.

In [1]:
bill = 54.98
print("Your bill is {}".format(bill))
Your bill is 54.98

Width of 8.

In [2]:
bill = 54.98
print("Your bill is {:8}.".format(bill))
Your bill is    54.98.

Width of 8 and left aligned.

In [3]:
bill = 54.98
print("Your bill is {:<8}.".format(bill))
Your bill is 54.98   .

Width of 8 and 4 after decimal.

In [4]:
bill = 54.98
print("Your bill is {:8.4f}.".format(bill))
Your bill is  54.9800.

f-strings

The f-strings are the advancement of the format() method. The ‘f’ is used at the beginning of the string, and we can put items at the placeholder.

In [1]:
first_name = "Steve"
last_name = "Jobs"
print(f"How are you {first_name} {last_name}.")
How are you Steve Jobs.

f-string for width and alignment

In [1]:
bill = 54.98
print(f"Your bil is {bill}")
Your bil is 54.98
In [2]:
bill = 54.98
print(f"Your bil is {bill:10.5f}")
Your bil is   54.98000

Template String

Template strings are a feature introduced in Python 3.6 through the string module. They provide a simplified syntax for string formatting, making it more readable. Unlike other string formatting methods like % formatting or str.format(), template strings use a simple syntax that aligns with the principles of readability and simplicity.

Simple use of Template String

In [1]:
from string import Template

name = "Steve"
age = 45

template = Template("My name is $name, and I am $age years old.")
result = template.substitute(name=name, age=age)

print(result)
My name is Steve, and I am 45 years old.

Resources

Handwritten Notes

References

  1. Python String format()
  2. Python String format() Tutorial
  3. String formatting in Python