添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

Why do I get "TypeError: not all arguments converted during string formatting" trying to substitute a placeholder like {0} using %?

Ask Question

I have some code which will read two strings from the user:

name1 = input("Enter name 1: ")
name2 = input("Enter name 2: ")

Later, I want to format those strings into a longer string for printing:

if len(name1) > len(name2):
    print ("'{0}' is longer than '{1}'"% name1, name2)

But I get an error message that looks like:

Traceback (most recent call last):
  File "program.py", line 13, in <module>
    print ("'{0}' is longer than '{1}'"% name1, name2)
TypeError: not all arguments converted during string formatting

What is wrong with the code? How should I write this line instead, in order to format the string properly?

See also String formatting: % vs. .format vs. f-string literal for in-depth comparison of the most common ways to do this kind of string formatting, and How do I put a variable’s value inside a string (interpolate it into the string)? for a general how-to guide for this kind of string construction. See Printing tuple with string formatting in Python for another common cause of the error.

Old-style % formatting uses % codes for formatting:

# A single value can be written as is:
'It will cost $%d dollars.' % 95
# Multiple values must be provided as a tuple:
"'%s' is longer than '%s'" % (name1, name2)

New-style {} formatting uses {} codes and the .format method. Make sure not to mix and match - if the "template" string contains {} placeholders, then call .format, don't use %.

# The values to format are now arguments for a method call,
# so the syntax is the same either way:
'It will cost ${0} dollars.'.format(95)
"'{0}' is longer than '{1}'".format(name1, name2)
                suppliment to @JinSnow comment.. if you want the variable name also to be printed, f"'It will cost {your_variable=} dollars."
– Sam Daniel
                Nov 9, 2021 at 9:56

The correct way to use traditional string formatting using the '%' operator is to use a printf-style format string (Python documentation for this here: http://docs.python.org/2/library/string.html#format-string-syntax):

"'%s' is longer than '%s'" % (name1, name2)

However, the '%' operator will probably be deprecated in the future. The new PEP 3101 way of doing things is like this:

"'{0}' is longer than '{1}'".format(name1, name2)
                scnr: "will probably be deprecated in the future" did not happen so far (Python 3.5). The old '%' syntax wasn't deprecated in 3.1 and only in 3.2 logging module learned how to format with the new style {}. And suddenly 3.5 brings PEP 461: % formatting for bytes. This makes me think the % remains for a long time to come.
– cfi
                Jan 7, 2016 at 16:03
                @LenarHoyt How do you feel about f-strings?  I can't imagine that is "'%s' is longer than '%s'" % (name1, name2) more concise than f"'{name1}' is longer than '{name2}'"
– Mark Moretto
                Jan 16, 2020 at 12:34
                I'm all for f-strings, but they're too new and you can't use them on project that is more than a year old
– Darko Kolev
                Sep 29, 2020 at 11:27

This error is also caused when trying to format a single value into the string using %, if the value is a tuple.

As shown and explained in Alex Martelli's answer there:

>>> thetuple = (1, 2, 3)
>>> print("this is a tuple: %s" % (thetuple,))
this is a tuple: (1, 2, 3)

Making a singleton tuple with the tuple of interest as the only item, i.e. the (thetuple,) part, is the key bit here.

I would rather convert the tuple to a string using one of the following statements: print("this is a tuple: %s" % str(thetuple)) or print("this is a tuple: %s" % repr(thetuple)) – Alex Mar 7, 2017 at 6:56

Keep in mind this error could also be caused by forgetting to reference the variable

"this is a comment" % comment #ERROR

instead of

"this is a comment: %s" % comment

In python 3.7 and above there is a new and easy way. It is called f-strings. Here is the syntax:

name = "Eric"
age = 74
f"Hello, {name}. You are {age}."

Output:

Hello, Eric. You are 74.

For me, as I was storing many values within a single print call, the solution was to create a separate variable to store the data as a tuple and then call the print function.

x = (f"{id}", f"{name}", f"{age}")
print(x) 
                This refers to an unrelated problem. Please see e.g. stackoverflow.com/questions/15496408.
– Karl Knechtel
                Apr 4 at 0:39

I encounter the error as well,

_mysql_exceptions.ProgrammingError: not all arguments converted during string formatting 

But list args work well.

I use mysqlclient python lib. The lib looks like not to accept tuple args. To pass list args like ['arg1', 'arg2'] will work.

Why do I get "TypeError: not all arguments converted during string formatting" trying to check for an even/odd number? See more linked questions