In chapter 5 of Python Tutorial, we will learn about String Formatting
Take a look at the below text:
“Python is a ___ language”
Now, we need to insert a word (variable if we are talking in Python language) in the above text to complete it. Correct?
This process of inserting a variable into a predefined text is known as string formatting. Currently, there are 5 ways you can perform string formatting.
Here are the 5 ways of string formatting:
- Formatting with % Operator.
- Formatting with format() string method.
- Formatting with string literals, called f-strings.
- Formatting with String Template Class
- Formatting with center() string method.
To keep chapter 5 tutorial as basic as possible, we will look at two of the most basic string formatting so that you can get a grip on it.
We will learn about string formatting using modulo % Operator and format() method in chapter 5 of Python tutorial. In the upcoming tutorials, we will learn about the remaining ways of string formatting.
modulo % operator:
Let’s start string formatting using modulo % operator. It is the oldest way of string formatting.
Remember the earlier example I mentioned above:
“Python is a ___ language”
In the above text, instead of the blank line, we use argument specifiers like “%s” and “%d.
Now, to complete string formatting using “%” operator, we write the code as below:
# This prints out "Python is a programming language"
text = "programming"
print("Python is a %s language" % text)
#It can be written in this way also
print("Python is a %s language" %'programming')
Click on “Run” to execute the code and get the output on the right-hand shell window
Let’s try using multiple argument specifiers:
# This prints out "Smith was born in year 1991"
year = 1991
print("%s was born in year %d" % ('Smith', year))
#It can be written in this way also
name = "Smith"
year = 1991
print("%s was born in year %d" % (name, year))
As you can see above, argument specifiers for word and integer are different. Below are the argument specifiers and their usage information
- %s – String
- %d – Integers
- %f – Floating point numbers
- %.f – Floating point numbers with a fixed amount of digits to the right of the dot.
- %x/%X – Integers in hex representation (lowercase/uppercase)
Please come up with your own text and perform string formatting to get a better understanding. You can practice in the above IDE windows or I will provide a blank IDE window at the end of this chapter 5 tutorial.
format() Method:
Python 3 introduced the Format() function to handle string formatting more effectively.
Let’s take the same example as the one taken in modulo % operator:
“Python is a __ language”
In the above text, instead of the blank line, we use curly braces {} as a placeholder and then we call .format() method on the variable to the placeholder. Please take a look at the example below:
# This prints out "Python is a programming language"
text = "programming"
print("Python is a {} language".format(text))
#It can be written in this way also
print("Python is a {} language".format('programming'))
Moving ahead in chapter 5, we can insert variables by index-based position or by assigning keywords in .format() method.
Let’s look at index-based position example:
# This prints out "Hello Alex, your current balance is 457.60"
print('Hello {0}, your {1} balance is {2:.2f}'.format('Alex', 'current', 457.5980))
The positions where the corresponding values will be inserted are indicated by the curly brackets {} with indices within the string {0} {1} {2:.2f}.
In the above example, {0} is placeholder for 0th argument ‘Alex’, {1} is placeholder for 1st argument ‘current’ and {2:.2f} is placeholder for 2nd argument, which is a floating number, 457.5980
To explain further about this placeholder {2:.2f}, it places floating number 457.5980 in its place and performs the operation .2f.
f specifies the format is dealing with a float number. If not correctly specified, it will give out an error.
The part after the “.” (2) truncates the decimal part (5980) up to the given number. In this case, 5980 is truncated after 2 places. Remaining numbers (59) is rounded off outputting 60.
Let’s look at assigning keywords example:
# This prints out "Hello Alex, your current balance is 457.60"
print("Hello {name}, your {cur} balance is {bal:.2f}".format(name='Alex', bal=457.5980, cur='current'))
You can see the difference between positional and keyword arguments as we have used the same example.
Here, we’ve used a keyword for the parameters. Namely, name=’Alex’, bal=457.5980 and cur = ‘current’.
As explained above, the placeholder {bal:.2f} is replaced by the value 457.5980. But before replacing it, it performs .2f operation on it. The decimal part is truncated after 2 places and remaining digits are rounded off. This outputs 457.60.
If you like to do more practice, I am providing blank IDE below, please make full use of it:
That brings to the end of chapter 5 of Python tutorial, however, there is lot more to cover in string formatting. We will cover the remaining topics in upcoming tutorials.
Assignment:
I am providing a text with blank spaces. Using the modulo % operator, you need to fill the spaces with argument specifiers such as %s, %d, etc.,
data = ("Alex's", 10, "beautiful")
#replace blank spaces with argument specifiers
blank_string = "____ house is on street number ____ and it is very ____"
print(blank_string %data)
data = ("Alex's", 10, "beautiful")
#replacing blank spaces with argument specifiers
blank_string = "%s house is on street number %d and it is very %s"
print(blank_string %data)
Give your best and try to resolve the assignment in chapter 5 tutorial. All the Best!!!
By the way, if you haven’t installed Python and Pycharm IDE on your Windows laptop, you can visit the below links to learn on how to install and configure/install Python and Pycharm IDE on Windows OS. This might be helpful in understanding the Python language easier.
How to Install Python 3 and Pycharm IDE on Windows
How to configure Pycharm IDE and “Run” your first Python 3 program
For your reference, to download Pycharm IDE, visit below link:
https://www.jetbrains.com/pycharm/download/?section=windows
However, if you don’t want to go through installation process, you can practice your learnings on this page itself by using integrated Python IDE above.
If you have any questions or comments about chapter 5 of Python tutorial, please let us know in the comments section below.