In the context of this exercise, can we utilize both keyword and positional arguments in the format() method?
Answer
Yes, you can use both keyword and positional arguments in the same format() method call.
When using both types of arguments, all the positional arguments must come first, before all the keyword arguments. The positional arguments will apply just to the {} without any keywords first, and then the keyword arguments will apply to the corresponding {} containing the keyword.
Example
string = "{}, {a}, {}".format(20, 30, a=40)
# First, the positional arguments 20 and 30
# replace the {} in order.
# Then the keyword argument is placed at {a}.
# This will result in:
print(string) # 20, 40, 30
On a sidenote, i feel CodeAcademy should amend this exercise, just for better readability & clarity. The arguments passed to the function & the key names should be kept different, otherwise it gets all jumbled up, the keys, the arguments, the values.
For example, the arguments passed to poem_description() could be pd, a , t & ow & key values could accordingly be pd, a, t & ow as well.
I agree: I feel like this exercise is badly designed and isn’t very demonstrative.
Their solution is also producing so much unnecessary code…
it’s just bad habit when we could simply skip all of this:
author = "Shel Silverstein"
title = "My Beard"
original_work = "Where the Sidewalk Ends"
publishing_date = "1974"
And do this:
def poem_description(publishing_date, author, title, original_work):
poem_desc = "The poem {title} by {author} was originally published in {original_work} in {publishing_date}.".format(publishing_date = publishing_date, author = author, title = title, original_work = original_work)
return poem_desc
print(poem_description(1974, "Shel Silverstein", "My Beard", "Where the Sidewalk End"))
I was so confused by the wording of the second exercise. Doesn’t teach anything when readability and clarity is indeed terrible. Really starting to regret signing up to Codecademy when the quality declined so much after loops and functions. The entire String chapter is rushed.
Your screenshot doesn’t show the code for the poem_description function.
At the bottom of the exercise, there is a “Copy to Clipboard” button. After copying the code, you can paste it in the forums using the </> button (see [How to] Format code in posts) .