Maison >développement back-end >Tutoriel Python >Comment résoudre l'erreur « TypeError : incompatibilité de formatage de chaîne » ?
Understanding the TypeError: String Formatting Mismatch
When trying to incorporate placeholders like {0} in string formatting, it's essential to understand the nuances of the formatting method being used. The error message "TypeError: not all arguments converted during string formatting" typically arises when the %-based formatting method is misused.
Old-style % Formatting
The % formatting method employs % codes to specify formatting operations. When formatting a single value, it can be included directly in the string:
<code class="python">'It will cost $%d dollars.' % 95</code>
However, for multiple values, a tuple must be provided:
<code class="python">"'%s' is longer than '%s'" % (name1, name2)</code>
New-style {} Formatting
In contrast, the {} formatting method utilizes {} placeholders and the .format() method. It's crucial to avoid mixing these methods. If the "template" string contains {} placeholders, use .format(), not %.
<code class="python"># Values as method arguments 'It will cost ${0} dollars.'.format(95) "'{0}' is longer than '{1}'".format(name1, name2)</code>
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!