Advanced Python String Formatting | Better Programming

A dummy image for better reading and navigation
Photograph by Carl Heyerdahl on Unsplash

On this article, you’ll study string formatting and how one can create a properly formatted variable string whether or not utilizing easy concatenation or in a extra skilled manner utilizingformat() perform. The “Variable” phrase has been used right here as a result of in lots of instances you would possibly have to create a string with placeholders that you simply wish to change in keeping with the out there information. Now with none additional delay allow us to get began.

Desk of Contents

  1. String Concatenation
  2. format() Function
  3. format() Function with Dictionaries and Lists
  4. format() Function with Classes Objects
  5. format() Function with Keyword Arguments
  6. format() Function With Numbers
  7. format() Function With Dates and Times

To create a string together with your information you need to use string concatenation as follows.
Allow us to assume we’ve a dictionary that represents the details about a scholar and also you wish to print this info in a single sentence.

scholar = 'identify': 'Adam', 'age': 22, 'yr': 4info = 'The coed identify is ' + scholar['name'] + ', he's ' + str(scholar['age']) + ' years previous and he's within the ' + str(scholar['year']) +'th yr'print(info)

Output:

The coed identify is Adam, he's 22 years previous and he's within the 4th yr

You may see that the earlier manner isn’t simply readable and you probably have an integer it is advisable solid it to a string. Additionally, you need to bear in mind the areas. Subsequently, it’s a must to use a extra sensible manner and that’s why you’ll study format().

To make use of it, all you want is so as to add curly braces to your string sentence and cross the knowledge to the format() perform within the order that you really want.

scholar = 'identify': 'Adam', 'age': 22, 'yr': 4info = 'The coed identify is  , he's  years previous and he's within the  th yr'.format(scholar['name'], scholar['age'], scholar['year'])print(info)

Output:

The coed identify is Adam , he's 22 years previous and he's within the 4 th yr

Additionally, you possibly can quantity the order of placeholders. That is helpful when you might have values that can repeat. Assume that the scholar’s e mail consists of the first_name and the last_name, and also you wish to print the e mail with the first_name and the last_name, so that you don’t have to cross them once more.

scholar = 'first_name': 'Adam', 'last_name': 'Smith'info = 'The coed identify is 0 1, and his e mail @e mail.com">0_1@e mail.com'.format(scholar['first_name'], scholar['last_name'])print(info)

Output:

The coed identify is Adam Smith, and his e mail Adam_Smith@e mail.com

You may as well entry the dictionary fields instantly within the curly braces after which cross the dictionary object to the format() perform with no need to explicitly decide the dictionary’s keys within the format() perform.

scholar = 'first_name': 'Adam', 'last_name': 'Smith'info = 'The coed identify is 0[first_name] 0[last_name], and his e mail 0[first_name]_0[last_name]@e mail.com '.format(scholar)print(info)

Output:

The coed identify is Adam Smith, and his e mail Adam_Smith@e mail.com

Additionally, you need to use the identical factor with lists

student_list = ['Adam', 'Smith']info = 'The coed identify is 0[0] 0[1], and his e mail 0[0]_0[1]@e mail.com'.format(student_list)print(info)

Output:

The coed identify is Adam Smith, and his e mail Adam_Smith@e mail.com

Assume we’ve a Pupil class that has these occasion attributes

  • Title of the scholar
  • Age of the scholar
  • The yr that he’s in
class Pupil:
def __init__(self, identify, age, yr):
self.identify = identify
self.age = age
self.yr = yr

Now, allow us to create an object from the Pupil class and print the values of its attributes.

s1 = Pupil('Adam', 23, 5)info = 'The coed identify is 0.identify, his age is 0.age and he's within the 0.yearth yr'.format(s1)print(info)

Output:

The coed identify is Adam, his age is 23 and he's within the fifth yr

You may cross key phrase arguments to the curly braces as follows.

info = 'The coed identify is identify, his age is age and he's within the yearth yr'.format(identify='Adam', age=22, yr=4)print(info)

Output:

The coed identify is Adam, his age is 22 and he's within the 4th yr

Additionally, you possibly can unpack the dictionary and use the key phrase arguments with it.

scholar = 'identify': 'Adam', 'age': 22, 'yr': 4info = 'The coed identify is identify , he's age years previous and he's within the yearth yr'.format(**scholar)print(info)

Output:

The coed identify is Adam , he's 22 years previous and he's within the 4th yr

Generally we’ve numbers that don’t have the identical variety of digits, however we wish to print them in a fantastic manner the place all of them have the identical variety of digits by including main zeros. We are able to do this by including a colon adopted by the variety of digits within the curly braces.

numbers = [1, 7, 15, 100]for x in numbers:
print('the quantity is :03'.format(x))

Output:

the quantity is 001
the quantity is 007
the quantity is 015
the quantity is 100

Additionally, if we’ve a big quantity, you possibly can separate the digits utilizing commas to make it extra readable.

print('the quantity is :,'.format(5000000000000))

Output:

the quantity is 5,000,000,000,000

Some float numbers have many decimal digits, and if you do not need to print all of them, you possibly can specify the variety of decimal digits as follows.

e = 2.7182818284590452353602874713526
print('the quantity is :.3f'.format(e))

Output:

the quantity is 2.718

format() perform helps you additionally cope with dates and occasions and print them in the way in which that you really want. So, allow us to create a DateTime object and print it on this manner “Month day, yr — hours: minutes: seconds”.

import datetimeobj = datetime.datetime(2022, 4, 5, 11, 25, 17)
info = ':%B %d,%Y - %H : %M : %S'.format(obj)
print(info)

Output:

April 05,2022 - 11 : 25 : 17

You may be taught extra concerning the symbols utilized in date and time formatting here.

That’s it !! allow us to transfer on now to the article abstract.

More Posts