Python String Formatting - Type Error - Not enough arguments for format string

纵饮孤独 提交于 2019-12-20 04:38:12

问题


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.


回答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))



回答2:


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.



来源:https://stackoverflow.com/questions/43708139/python-string-formatting-type-error-not-enough-arguments-for-format-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!