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