Access two values in format() formula

I am developing some code and I want to access to two vaules when you use the format() formula. When I use this formula in Spyder:

response, play =  "My name is {0}".format("John")

I get this Error:

ValueError: too many values to unpack (expected 2)

I want to know it there is way to obtain the two values. I am expecting when I use the formula to get the next value

response = "My name is {0}"
play = "John"

3 answers

  • answered 2020-06-27 03:51 MrNobody33

    You could try

    play = "John"
    response = f"My name is {play}"

    Same as:

    play,response = "John","My name is {0}".format(play)

  • answered 2020-06-27 03:57 Brett Lapierre

    If MrNobody33 has not answered your question you may consider reviewing tuple unpacking or assigning multiple variables.

    response, play = "My name is {0}".format("John"), "Other name is {0}".format("Brett")

  • answered 2020-06-27 05:30 Steven

    Strictly speaking, if you want that result you would just use

    response, play = "My name is {0}", "John"

    Since you're assigning to 2 variables on the left, you need 2 equivalent values on the right, but you only offer one. Your code of "My name is {0}".format("John") translates to 'My name is John' which is a single string value. Python doesn't know which of the two variables on the left it should assign this to, or what to do with the other one. Hence it was expecting too many values (2) for the number you provide (1).

    If you actually meant that you wanted:

    response = "My name is John"
    play = "John"

    then you would use:

    response, play = "My name is {0}".format("John"), "John"

    Assuming you had "John" in a variable:

    name = "John"
    response, play = "My name is {0}".format(name), name

    If you're using Python 3.6+, f-strings are cooler:

    response, play = f"My name is {name}", name

    Either way, the point is if you're assigning to n variables on the left, you need n separate values on the right.