Related Articles

Related Articles

Formatting containers using format() in Python
  • Last Updated : 02 Sep, 2020

Let us see how to format containers that were accessed through  __getitem__ or getattr() using the format() method in Python.

Accessing containers that support __getitem__

a) For Dictionaries

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# creating a dictionary
founder = {'Apple': 'Steve Jobs', 'Microsoft': 'Bill Gates'}
  
# formatting
print('{f[Microsoft]} {f[Apple]}'.format(f = founder))

chevron_right


Output :

Bill Gates Steve Jobs

f[Microsoft] is replaced by Bill Gates and f[Apple] is replaced by Steve Jobs.

b) For lists

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# creating a list
list_items = [1, 3, 5, 7, 9, 11]
  
# formatting
print('{l[3]} {l[5]}'.format(l = list_items))

chevron_right


Output :

7 11

Accessing attributes on objects that support getattr()

a) For Class

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# creating a class
class Program(object):
    language = 'Python'
  
# formatting
print('{p.language}'.format(p = Program()))

chevron_right


Output :



Python

p.language is replaced by Python as language is an attribute of Program

Accessing the nested structure

Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# creating a clas
class Program(object):
    language = 'Python'
      
    # creating a dictionary
    versions = [{'version': '1'}, {'version': '2'}, {'version': '3'}]
  
# formatting
print('{p.language}: {p.versions[2][version]}'.format(p = Program()))

chevron_right


Output :

Python: 3

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :