简体   繁体   中英

Python — TypeError: format() takes at most 2 arguments (3 given)

I'm taking an intro course to Python3 by SoloLearn. This is a code example they give, but when I run it in Python3 or in Python2, I get similar errors. Here's the code, on introduction to String Formatting:

nums = [4, 5, 6]
msg = "Numbers: {0} {1} {2}".
format(nums[0], nums[1], nums[2])
print(msg)

which is supposed to result in:

>>>
Numbers: 4 5 6
>>>

But I get a Syntax Error on line 2, which points to the "." at the end of the line as being an invalid use of syntax.

And I get the TypeError: format() takes at most 2 arguments (3 given) when I try to execute line 3.

Why!?

Lines 2 and 3 should be one line:

msg = "Numbers: {0} {1} {2}".format(nums[0], nums[1], nums[2])

If the code had that line break in the actual course, they need to get their act together. If you introduced the line break, don't do that.

If you want to put the format in another line, you either have to put a backslash like this:

msg = "Numbers: {0} {1} {2}".\
format(nums[0], nums[1], nums[2])

or wrap it with parenthesis, or better yet, put the format in the same line

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM