Why do I get "TypeError: not all arguments converted during string formatting" trying to substitute a placeholder like {0} using %?
output-formatting, python, python-3.x, string, typeerror
Solution
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)
Problem
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.
Related problems
- Why do I get "TypeError: not all arguments converted during string formatting" trying to format a tuple?
- How do I put a variable’s value inside a string (interpolate it into the string)?
- String formatting: % vs. .format vs. f-string literal
- Why do I get "TypeError: not all arguments converted during string formatting" trying to check for an even/odd number?