I’m trying to print a message comparing two input strings using string formatting.
However, when I mix % formatting with {} placeholders, I get the error TypeError: not all arguments converted during string formatting
.
What causes this mismatch, and how should I correctly format the string in this situation?
Ah yes, I’ve hit this exact error before! The problem is you’re mixing two different string formatting styles. The {0}
and {1}
syntax is for the .format()
method, not for % formatting. So when you do something like:
print("'{0}' is longer than '{1}'" % (name1, name2))
Python gets confused - it expects %s
, not {}
. You should either use one or the other.
For %
, do:
print("'%s' is longer than '%s'" % (name1, name2))
Or better yet, switch fully to .format()
:
print("'{}' is longer than '{}'".format(name1, name2))
You’re not alone - I see this a lot with students new to Python. Basically, % formatting is the old-style method and doesn’t understand {} placeholders.
The error happens because Python tries to insert values where it finds %, but it can’t parse the {0} - it’s expecting %s, %d, etc.
To keep things clean, I’d recommend using .format() or f-strings if you’re on Python 3.6+:
print(f"'{name1}' is longer than '{name2}'")
Much more readable and modern!