top of page
Revathy Krishna

How to format Strings using print() in Python?


Knowing how to display output is very important when implementing a concept in programming. When you know how to access a data in your program, most of the problems can be cracked and that's why print() function has a very big role in debugging too. The print() function in Python 3 is the upgraded version of print statement in Python 2.

String formatting is a very useful concept in Python both for beginners and advanced programmers .

When looking into String formatting the first concept coming into mind is String Concatenation. But string concatenation is not the only way to use in Python. as you know, Python always have a simpler solution.


What is String concatenation?

String concatenation is joining strings end to end. The simplicity of string concatenation depends on the strings that are joined. Strings means not just Strings, it also include data from collection data types like lists, dictionaries,etc.

Consider a simple String Concatenation:

my_string1 = "Hello"
my_string2 = "World"
result = my_string1 + my_string2
print(result)

Output will be:

HelloWorld

But when it come to variables and other data structures in Python, string concatenation becomes more complex.

Consider the below statement:


employee = {'name': 'David', 'age': '45', 'salary': '5000.00'}
print("Employee name is "+ employee['name'] + " of age "+ str(employee['age']) + " and salary is ") + employee['salary'])

Output:


Employee name is David of age 45 and salary is 5000.00

The above output format is based on string concatenation. But there are 3 other string formatting techniques Python offer, which are more useful in different situations. In this blog , I am trying to include the syntax and techniques which I found more useful.


Formatting Strings Using print():


How can you print variables in Python?

The answer is Simple. Just include variable names in the print statement separated by commas.

Consider an example:


# Variables of different datatypes
name = "David"
age = 45
salary = 5000.00
print(name,age,salary)

Output:


David 45 5000.0

But while displaying output or creating a log report we may need to format this output in various format.

There are 3 ways of formatting Strings using print() function.

  1. Using ' %'

  2. Using .format

  3. Using f'string

Each form has its own uses.


Using '%' or C- style String Formatting:

In this style, we use the '%' operator to format strings . For the above example, we can format the string as follows where

  • %s for Strings

  • %d for integer

  • %f for float


# %s is for Strings, %d for integer , %f for float
print("My name is %s and I am %d years old"%(name, age))
# %0.2f is to display 2 decimal points
print("My salary is %0.2f"%(salary))
# Another example of float
print("The value of pi is %f \n Short pi is %0.2f"%(math.pi, math.pi))

Output:


My name is David and I am 45 years old
My salary is 5000.00
The value of pi is 3.141593 
Short pi is 3.14

Using .format:

In this method of using .format, {} is used as placeholder for variables. The {} will be replaced by the variable value in the order it is specified.For the above example, the print statement using format is as follows:


# Using .format
print("My name is {} and I am {} years old. My income is {} per \
month".format(name, age, salary))

Note: Here '\' is used to indicate that the print statement is extended to the next line.


Output:


My name is David and I am 45 years old. My income is 5000.0 per month

Another advantage of using placeholders is , we can explicitly number the placeholders, say {0},{1}, etc. Consider the above example,here I am explicitly giving name {0} and age {1} . We can use {0} ,{1} in any number of places in the statement but we need to specify that only once in the format function. Please ignore if the sentence doesn't make any sense.


# Explicitly number {}
print("My name is {0} and I am {1} years old. People call me {0}.".format(name, age))

Output:


My name is David and I am 45 years old. People call me David.

Another example using dictionary:


# Dictionary, using format
employee = {'name': 'David', 'age': '45', 'salary': '5000.00'}
print("Employee name is {name} of age {age} and salary is {salary}".format(**employee))

Here, the key names are substituted and so the order at which they are used doesn't matter

# Order of keys can be different
print("{name} get {salary} salary and he is {age} years old".format(**employee))

Output:


Employee name is David of age 45 and salary is 5000.00
David get 5000.00 salary and he is 45 years old

Using f' string:

This is one of the most recommended formatting methods. It is quite simple to use and has more functionality like perform calculations within {}. This f- string format can be assigned to variables as well


# Using f string
message = f'Hey I am {name} and I am {age} years old '
print(message)
# Or within print()
print(f'Hey I am {name} and I am {age} years old ')

Both gives same output


Hey, I am David and I am 45 years old 
Hey, I am David and I am 45 years old 

Now , the f'string solution for the dictionary example is,


employee = {'name': 'David', 'age': '45', 'salary': '5000.00'}
print(f"Employee name is {employee['name']} of age {employee['age']} and salary is {employee['salary']}")

Arithmetic calculations are supported within f'string. For example


# Calculation within f'string
radius = 10
print(f"Area of the circle is {math.pi * radius**2}")

Output:


Area of the circle is 314.1592653589793

If we need formatting in decimal points , f'string supports that as well


# Formatting the float
radius = 10
print(f"Area of the circle is {math.pi * radius**2:.2f}")

Output:


Area of the circle is 314.16

Hope this gives an overall introduction on the String Formatting Techniques in Python.

If you find this blog helpful, please leave a clap. Thank you.

23,781 views
bottom of page