String Formatting in Python

In the previous article, we saw the use of escape sequences and raw strings now let us discuss Formatted Strings in Python, When we want to print formatted data, suppose combining multiple strings we can use the + operator.

For example:

print("Welcome " + "to " + "CodeKyro!")

While something like this would work in practice, it would require a lot of plus operator signs and additional spaces. To avoid using these + operators we have formatted strings and in Python, there are three ways to deal with using formatted strings.

String Formatting in Python

The three ways in which we can use formatted strings in Python are:

  1. Using % (Like C language) : This style is followed in older languages like C where we use percentage operator.
course="Python Code"
s="Welcome %s to the %s "% (name,course)
Welcome ABC to the Python Code 

The %s acts similar to a placeholder and the variables are placed in respective order and substitute these placeholders during output.

2. Using format( ) function: This method of using the format( ) function is generally recommended over using the % older style method. The numbers like (0) or (1) can be used in any order to change the positioning of the variable values within the statement.

course="Python Code"
s="Welcome {0} to the {1}".format(name, course)

For number 0, the value of variable ‘name’ will appear and for number 1 the value of ‘course’ will appear.

3. Using f-string: It is the best and most modernized approach out of all the three. The format is declared in a similar way to the declaration of raw strings but using the alphabet f instead.

course="Python Code"
s=f"Welcome {name} to the {course}"

The output of all three programs and methods are the same. Let us look at some more f-string methods:

We can use expressions with f-string values:

a = 10
b = 20
print(f"Sum of {a} and {b} is {a+b}")
print(f"Product of {a} and {b} is {a*b}")
Sum of 10 and 20 is 30
Product of 10 and 20 is 200

The expressions are evaluated at run-time, we can also call methods in f-strings:

print(f"Lower Case of {s1} is {s1.lower()}")
print(f"Upper Case of {s1} is {s1.upper()}")
Lower Case of ABC is abc
Upper Case of ABC is ABC

So it is possible to write and refer to various functions or methods for dealing with various string operations. For example, in the earlier addition and multiplication program instead of using expressions, we could simply make use of functions to perform all the required operations. So, we have seen the various and optimal ways in utilizing formatted strings in Python. In the next article, we will look at various String operations in Python.

Leave a Comment