Can we utilize both keyword and positional arguments in the format() method?


#1

Question

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