Use Named Arguments in Format Strings - dummies

By John Paul Mueller

Format strings are incredibly flexible in Python. You can use them to perform all sorts of output tricks by using the correct formatting features. In addition, format strings offer a number of ways to access the output values. The following steps demonstrate these techniques and help you understand why named arguments are so special.

1Open a copy of the Python Shell.

You see the Python Shell window.

2Type "My {} is {}. My {} is {}.".format("car", "blue", "truck", "blue") and press Enter.

The output shows that each of the values is entered in the precise order it appears in the format() call. You can’t change anything about this particular output ordering. In addition, you must enter repetitive values. The value blue must appear twice because you have no means to tell Python how to format the string otherwise.

3Type "My {0} is {1}. My {2} is {1}.".format("car", "blue", "truck") and press Enter.

The output is the same. However, if you use the numbered entries, you can get by without typing the value blue twice. The entries must still appear in a specific order. You can’t simply type them in the format() call in any order that appeals to you.

4Type "My {Veh1} is {Color}. My {Veh2} is {Color}.".format(Color = "blue", Veh1 = "car", Veh2 = "truck") and press Enter.

The output is still the same, but using named arguments has the additional benefit of letting you type the values in any order you want. So the advantages of named arguments are that you don’t need to repeat information, nor do you have to enter it in any specific order. Of course, there is a another benefit that you might not have thought about. When the entries are unnamed or simply use numbers, documenting them is hard. In addition, someone following behind you might not have any idea of what they should contain. In this case, you see that using the named arguments makes things much clearer. The downside to this approach is that more typing is involved.

5Type "My {Veh1[0]} is {Color}. My {Veh2[0]} is {Color}.".format(Color = "blue", Veh1 = "car", Veh2 = "truck") and press Enter.

The output changes to show just the first letter of each vehicle. However, what is being shown is made clearer by using the named argument. If the named argument weren’t in place, you might have a hard time figuring out what you were seeing.

6Close the Python Shell.

That’s all there is to formatting a string in Python.