1
-
2
1
Not using dict keys when formatting strings
3
2
===========================================
4
3
@@ -7,7 +6,10 @@ When formatting a string with values from a dictionary, you can use the dictiona
7
6
8
7
.. code :: python
9
8
10
- person = {' first' :' Tobin' , ' age' :20 }
9
+ person = {
10
+ ' first' : ' Tobin' ,
11
+ ' age' : 20
12
+ }
11
13
12
14
13
15
Anti-pattern
@@ -17,13 +19,30 @@ Here is an example of formatting the string with values from the person. This is
17
19
18
20
.. code :: python
19
21
20
- person = {' first' :' Tobin' , ' age' :20 }
21
- print (' {0} is {1} years old' .format(person[' first' ], person[' age' ])) # bad
22
- # >>> Tobin is 20 years old
22
+ person = {
23
+ ' first' : ' Tobin' ,
24
+ ' age' :20
25
+ }
26
+
27
+ print (' {0} is {1} years old' .format(
28
+ person[' first' ],
29
+ person[' age' ])
30
+ )
31
+ # Output: Tobin is 20 years old
23
32
24
- person = {' first' :' Tobin' , ' last' : ' Brown' , ' age' :20 }
25
- print (' {0} {1} is {2} years old' .format(person[' first' ], person[' last' ], person[' age' ])) # bad
26
- # >>> Tobin Brown is 20 years old
33
+ person = {
34
+ ' first' : ' Tobin' ,
35
+ ' last' : ' Brown' ,
36
+ ' age' :20
37
+ }
38
+
39
+ # Bad: we have to change the replacement fields within our string, once we add new values
40
+ print (' {0} {1} is {2} years old' .format(
41
+ person[' first' ],
42
+ person[' last' ],
43
+ person[' age' ])
44
+ ) # bad
45
+ # Output: Tobin Brown is 20 years old
27
46
28
47
29
48
Best practice
@@ -33,13 +52,21 @@ By using the dictionary keys in the string we are formatting, the code is much m
33
52
34
53
.. code :: python
35
54
36
- person = {' first' :' Tobin' , ' age' :20 }
55
+ person = {
56
+ ' first' : ' Tobin' ,
57
+ ' age' :20
58
+ }
59
+
37
60
print (' {first} is {age} years old' .format(** person))
38
- # >>> Tobin is 20 years old
61
+ # Output: Tobin is 20 years old
39
62
40
- person = {' first' :' Tobin' , ' last' : ' Brown' , ' age' :20 }
63
+ person = {
64
+ ' first' :' Tobin' ,
65
+ ' last' : ' Brown' ,
66
+ ' age' :20
67
+ }
41
68
print (' {first} {last} is {age} years old' .format(** person))
42
- # >>> Tobin Brown is 20 years old
69
+ # Output: Tobin Brown is 20 years old
43
70
44
71
45
72
Going even further, the same result can be achieved with your own objects by using ``obj.__dict__ ``.
@@ -59,4 +86,4 @@ Going even further, the same result can be achieved with your own objects by usi
59
86
60
87
person = Person(' Tobin' , ' Brown' , 20 )
61
88
print (person)
62
- # >>> Tobin Brown is 20 years old
89
+ # Output: Tobin Brown is 20 years old
0 commit comments