Format() with variable length list

Viewed 121

I am trying to understand the format() function in python while completing a codewars challenge. My solution was a lot less elegant as I used if statements to insert the phone number formatting at specific positions.

The top answer was:

def create_phone_number(n):
    return "({}{}{}) {}{}{}-{}{}{}{}".format(*n)

I understand that format() will replace each curly braces with whatever you enter as a parameter and the list length cannot be less than the number of braces. How does the format() function know to traverse the list at each position starting at n[0] and replace the empty curly braces when no variable is put in the string it is formatting?

1 Answers

* before n is for unpacking. That means it is transformed to a list of arguments. In the case of a string "1234" it is unpacked to its characters '1','2','3','4'

If all curly brackets are empty they are implicitly filled with indexed.

So "({}{}{}) {}{}{}-{}{}{}{}".format(*n) is equivalent to "({0}{1}{2}) {3}{4}{5}-{6}{7}{8}{9}".format(*n)

Indexed curly brackets is replaced with the corresponding argument of the format method. That means if you manually add indexes to the curly brackets, you can change the order in which the arguments should appear in the string and even insert the same argument several times.

You can read more in documentation for Format String Syntax

Related