Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialunderfish
3,226 PointsIt doesn't seem like you can use numbers as keys when formatting with kwargs. Am I doing this wrong or is this the case?
I recognize they are "keyword" args, but it still seems strange you can't use numbers (and I'm not sure what else) to format.
Example:
# throws IndexError: tuple index out of range
my_dict = {1: 'a', 2: 'b'}
my_string = "{1} comes before {2}."
my_string.format(**my_dict)
# works
my_dict = {'one': 'a', 'two': 'b'}
my_string = "{one} comes before {two}."
my_string.format(**my_dict)
Is there a way to escape the numbers in my_string?
[MOD: fix formating -cf]
1 Answer
Chris Freeman
Treehouse Moderator 68,454 PointsIn short, you cannot escape numbers to use as named fields.
The issue is using named fields vs positional fields. When format
sees a field with a number, such as {1}
, it expects positional list of arguments to fill the fields. This is useful if you have a repeated field:
>>> "{0} {1} {0}".format("Department", "Redundancy")
'Department Redundancy Department'
Using a positional unpacking works:
>>> my_string = "{0} comes before {1}."
>>> my_list = ['a', 'b']
>>> my_string.format(*my_list)
'a comes before b.'
EDIT: thought of an additional way to use a dictionary:
>>> my_dict = {0: 'a', 1: 'b'}
# Change field names to expect dictionary
>>> my_string = "{dct[0]} comes before {dct[1]}."
>>> my_string.format(dct=my_dict)
'a comes before b.'
Other usage examples in the docs
Chris Freeman
Treehouse Moderator 68,454 PointsChris Freeman
Treehouse Moderator 68,454 PointsEDIT: Added additional dictionary usage.
underfish
3,226 Pointsunderfish
3,226 PointsAwesome, thanks.