Python not all arguments converted during string formatting

Question:

I have the following python code

table += '<tr><td>{0}</td><td>{1}</td></tr>'% format(str(key)), 
format(str(value))
TypeError: not all arguments converted during string formatting

What could be the problem?

Asked By: KMarto

||

Answers:

You have to call the .format method on the string. Just like this:

table += '<tr><td>{key}</td><td>{value}</td></tr>'.format(key=str(key), value=str(value))
Answered By: Tudor Plugaru

You are mixing three different methods of converting values to strings. To use the {..} placeholders, use the str.format() method, directly on the string literal that is the template:

table += '<tr><td>{0}</td><td>{1}</td></tr>'.format(key, value)

There’s no need to use the str() or format() functions, and you don’t need to use % either.

  • The format() function turns objects into a string using the format specification mini language, the same language that lets you format the values in a str.format() placeholder. It’s the formatting part of the template language, available as a stand-alone function.

  • str() turns an object into a string without specific formatting. You’ll always get the same result. Because str.format() already converts objects to strings (but with formatting controls) you don’t need to use this. And if you need it anyway (because, say, you want to apply string formatting controls and not those of another object type), str.format() has the !s conversion option.

  • Applying % to a string object gives you a different string formatting operation called *printf-style formatting. This method is much less flexible than the str.format() version.

If your are using Python 3.6 or newer I recommend you use the faster f-string formatting string literals:

table += f'<tr><td>{key}</td><td>{value}</td></tr>'
Answered By: Martijn Pieters
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.