@@ -19,9 +19,11 @@ Here is an example of formatting the string with values from the person. This is
19
19
20
20
person = {' first' :' Tobin' , ' age' :20 }
21
21
print (' {0} is {1} years old' .format(person[' first' ], person[' age' ])) # bad
22
+ # >>> Tobin is 20 years old
22
23
23
24
person = {' first' :' Tobin' , ' last' : ' Brown' , ' age' :20 }
24
25
print (' {0} {1} is {2} years old' .format(person[' first' ], person[' last' ], person[' age' ])) # bad
26
+ # >>> Tobin Brown is 20 years old
25
27
26
28
27
29
Best practice
@@ -33,9 +35,11 @@ By using the dictionary keys in the string we are formatting, the code is much m
33
35
34
36
person = {' first' :' Tobin' , ' age' :20 }
35
37
print (' {first} is {age} years old' .format(** person))
38
+ # >>> Tobin is 20 years old
36
39
37
40
person = {' first' :' Tobin' , ' last' : ' Brown' , ' age' :20 }
38
41
print (' {first} {last} is {age} years old' .format(** person))
42
+ # >>> Tobin Brown is 20 years old
39
43
40
44
41
45
Going even further, the same result can be achieved with your own objects by using ``obj.__dict__ ``.
@@ -55,3 +59,4 @@ Going even further, the same result can be achieved with your own objects by usi
55
59
56
60
person = Person(' Tobin' , ' Brown' , 20 )
57
61
print (person)
62
+ # >>> Tobin Brown is 20 years old
0 commit comments