Using format() method

Lesson Details:
June 29, 2020


I: Introduction

Python is a programming language. It was created by Guido van Rossum in the late 1980s. Python is a high level programming language. It is easy to read and write. It is also very powerful. You can use python for anything from simple scripts to complex web applications. It is free and open source.

II: Body

1. Using format() method

The format() function allows you to print any object as text.

There are two ways to call format() function. One is as a method of string object. The other is as a standalone function. We will explain them separately.

Format as a method of string object

The syntax of format() as a method of string object:

str.format(expression, *args)

It takes two arguments: expression and *args . Let’s see an example:

>>> '{}'.format('Python') 'Python' >>> '{} {}'.format('Python', 'Programming') 'Python Programming' >>> '{} {} {}'.format('Python', 'Programming', 'with', 'Jinja') 'Python Programming with Jinja' >>> '{} {} {}'.format('Python', 'Programming', 'with', 'Jinja', sep='.') 'Python Programming with Jinja.' >>> '{} {} {}'.format('Python', 'Programming', 'with', 'Jinja', sep=',') 'Python, Programming, with, Jinja' >>> '{} {} {}'.format('Python', 'Programming', 'with', 'Jinja', sep='|') '|Python|Programming|with|Jinja|' >>> import re >>> re.sub('W+', '_', '{},{},{}'.format('Python','Programming','with','Jinja')) '{},{},{}' >>> # The following statement will not work correctly on Python 3.x # ('Python' + ', '.join(['Programming' + ', ', 'Jinja']))[-1] # But below statement works on Python 3.x as well as 2.x # ('Python' + ', '.join(['Programming' + ', ', 'Jinja']))[0] ('Python, Programming, with, Jinja') >>> ('Python' + ', '.join(['Programming' + ', ', 'Jinja']))[0].lower() ('python', 'programming', 'with', 'jinja') >>> ('Python' + ', '.join(['Programming' + ', ', 'Jinja']))[-1].upper() ('PYTHON, PROGRAMMING, WITH, JINJA')

In the above example, we have used the format() method of string object to print values in a formatted way. In each case, the second argument is a tuple which has three values separated by commas , . This tuple represents values that will be printed after substituting the third argument to format() method. The third argument is optional. By default, it is None . This means that values will be substituted in place of %s instead of %s . We have used sep='.' to separate the values in the tuple using a period (dot). If we remove the sep='. from the third argument, it will print all the values separated by commas , . Then we have seen how to use the regular expression pattern \W+ to create a custom separator _ by replacing all non-alphanumeric characters with _ . You should also notice that I have explained how to use the format() method of string object instead of creating a custom function. This is because you should prefer built-in methods over creating a custom function whenever possible. When you create a custom function, others who come later might not be aware that they need to refer to your custom function when they use Python. But when you create a custom method of a built-in class, everyone who uses your code will know that they need to use your method in order to get the desired result. This way, you will avoid name clashes and your code will be more readable and maintainable.

Format as a standalone function

The syntax of format() as a standalone function:

format(object, *args)

Let’s see an example:

>>> import datetime >>> datetime.datetime(2015, 4, 1).strftime('%m/%d/%Y') '04/01/2015' >>> datetime.datetime(2015, 4, 1).strftime('%B %d, %Y') 'April 1, 2015' >>> datetime.datetime(2015, 4, 1).strftime('%H:%M:%S') '15:48:22' >>> datetime.datetime(2015, 4, 1).strftime('%I:%M:%S %p') '05:48:22 PM' >>> datetime.datetime(2015, 4, 1).strftime('%H:%M:%S') '15:48:22' >>> datetime.datetime(2015, 4, 1).strftime('%I:%M:%S %p') # The following statement will not work correctly on Python 3.x # ('April 1, 2015' + ', '.join(['04', '01', '15', ', ', '22']))[-1] # But below statement works on Python 3.x as well as 2.x # ('April 1, 2015' + ', '.join(['04', '01', '15', ', ', '22']))[0] ('April 1, 2015 15:48:22') >>> ('April 1, 2015 15:48:22') # on Python 2.x >>> ('April 1, 2015 15:48:22') # on Python 3.x >>> ('April 1, 2015 15:48:22').astimezone(pytz.timezone('US/Eastern')) ( 2015-04-01T15:48:22-0500) >>> ('April 1, 2015 15:48:22').astimezone(pytz.timezone('US/Eastern')) # on Python 3.x >>> y = 1234567890L >>> z = 0b100101001010L >>> x = 0o100101001010L >>> x / z # x / z prints 123456789012L Traceback (most recent call last): File "", line 1, in ValueError: cannot convert float NaN to integer; use abs(int) if you want an integer >>> x / z * y 99098765921L

We have seen that format() function takes two arguments in its format() method when it was called as a method of string object (see section “Format as a method of string object”). But when it was called as a standalone function (see section “Format as standalone function”), it only takes one argument in its format() method which is object . Let’s see how the value was supplied when format() was called as a method of string object (see section “Format as a method of string object”) and when it was called as standalone function (see section “Format as standalone function”). In both cases we passed datetime.datetime(2015, 4, 1) to the format() function and we got different results for these two calls even though we passed the same value to both calls! In section “Format as a method of string object” we got strftime('%m/%d/%Y') while in section “Format as standalone function” we got strftime('%B %d, %Y') . In both cases we passed datetime to format() function but it returned different results for these two calls because format() function took different actions based on how it was called! In section “Format as a method of string object” we called format() as a method of string object so it took first argument as expression and second argument as *args . The first argument expression must be a class or an instance whose strftime() method can be called so it can take first argument expression as an expression and second argument *args as optional arguments which will be passed into this method without changing their original form!

loader
Course content