1

So what's wrong with this string? I'm not able to figure out why it says there's not enough arguments for format string. I'm new to Python and just figuring things out.

Edit: This is not the same as the other question suggested. The other is trying to do some crazy array stuff that I am not even getting into. I just need to understand the basic concept of tuples and how string formatting works.

    data = ["John", 23, "United States", "United Kingdom"]
    format_string = "Your name is %s and you are %s years old. You were born in %s and are now living in %s."
    print(format_string %data)

Is it because I do not have enought "strings" inside? How do I have a single list with strings and numbers? For example, a JSON list.

2
  • This is because you're passing only the list which contains the objects that you want to format. So only one object gets formatted, the list itself. Commented Apr 30, 2017 at 15:43
  • Possible duplicate of How to use list (or tuple) as String Formatting value Commented Apr 30, 2017 at 16:00

2 Answers 2

1

If you pass the list in as a tuple, it should work just fine.

data = ["John", 23, "United States", "United Kingdom"]
format_string = "Your name is %s and you are %s years old. You were born in %s and are now living in %s."
print(format_string % tuple(data))
Sign up to request clarification or add additional context in comments.

6 Comments

Considering checking out this post.
Consider flagging this question as duplicate since the link's basically asking the same thing
@DigitalVeer - So what consists a tuple. Your answer worked for me. But I am a beginner and need to wrap my head around what a 'tuple' is so am keeping it open. A definition is not getting across to me. As far as I understand. I can mix data sets and strings and it seems to work fine. I do not need to use %d in this even though 23 is a number. Why? What differentiates a tuple from a regular list?
Googled it. tuples are immutable and lists are mutable. They are differentiated mostly with brackets vs square brackets
@coderx Don't take my word for it; however, I believe that if you use a mutable data type (e.x. a list), then it only takes the first value given by that data-type. However, using a immutable such as a tuple will ensure that all the patterns get matched. I'll look up why this behavior exists and get back to you.
|
1

The right operand of str.__mod__ must either be a tuple or a single value. Since it is not a tuple it is being interpreted as a single value whereas the format string requires a 4-tuple. Either convert data to a tuple or make it a tuple in the first place.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.