300

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.

9 Answers 9

297

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)
Sign up to request clarification or add additional context in comments.

2 Comments

in python 3.6: f"'It will cost ${your_variable} dollars."
suppliment to @JinSnow comment.. if you want the variable name also to be printed, f"'It will cost {your_variable=} dollars."
65

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)

7 Comments

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.
% is more concise. Glad it stays with us.
I concur. % is more concise and removing would add no benefit to the language.
@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}'"
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
|
59

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.

1 Comment

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))
8

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

Comments

4

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.

1 Comment

This doesn;'t actually answer the question.
0

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) 

Comments

0

Most Easy way typecast string number to integer

number=89
number=int(89)

1 Comment

This refers to an unrelated problem. Please see e.g. stackoverflow.com/questions/15496408.
0

You can also use f-strings to format a text with multiple arguments! But note this only work well on Python 3.6 and never.

Example Program (with f-strings)

import random
name = input("Your name> ")
umcount = random.randint(1,10)
greeting = f"Hello, {name}! You have {umcount} unread messages."
print(greeting)

Input:

Your name> John Doe

Example Output:

Hello, John Doe! You have 3 unread messages.

In python 3.6 and later, the f-strings feature allows you to have inputted texts, but it's better than old-style % formatting. When you declaring/using a f-strings, add a f before quotation of strings (e.g. f"Hello, {name}!). Now you can use your variables in f-strings as text arguments, in { and } blocks. For example, f"Hello, {name}! Your age is {age}!" will use name string and age integer to fill {name} and {age}. So if name is "John Doe" and age is 24, this string outputs Hello, John Doe! Your age is 24!.

Comments

-1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.