Skip to content

Commit 5953fbd

Browse files
committed
Add output examples
1 parent f82fbc3 commit 5953fbd

File tree

1 file changed

+5
-0
lines changed

1 file changed

+5
-0
lines changed

docs/readability/not_using_dict_keys_when_formatting_strings.rst

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,11 @@ Here is an example of formatting the string with values from the person. This is
1919
2020
person = {'first':'Tobin', 'age':20}
2121
print('{0} is {1} years old'.format(person['first'], person['age'])) # bad
22+
# >>> Tobin is 20 years old
2223
2324
person = {'first':'Tobin', 'last': 'Brown', 'age':20}
2425
print('{0} {1} is {2} years old'.format(person['first'], person['last'], person['age'])) # bad
26+
# >>> Tobin Brown is 20 years old
2527
2628
2729
Best practice
@@ -33,9 +35,11 @@ By using the dictionary keys in the string we are formatting, the code is much m
3335
3436
person = {'first':'Tobin', 'age':20}
3537
print('{first} is {age} years old'.format(**person))
38+
# >>> Tobin is 20 years old
3639
3740
person = {'first':'Tobin', 'last': 'Brown', 'age':20}
3841
print('{first} {last} is {age} years old'.format(**person))
42+
# >>> Tobin Brown is 20 years old
3943
4044
4145
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
5559
5660
person = Person('Tobin', 'Brown', 20)
5761
print(person)
62+
# >>> Tobin Brown is 20 years old

0 commit comments

Comments
 (0)