Quand dois-je utiliser des espaces réservés \'{}\' avec .format() au lieu de \'%s\' pour le formatage de chaîne en Python ?

Barbara Streisand
Libérer: 2024-10-18 12:54:30
original
724 Les gens l'ont consulté

When Should I Use \'{}\' Placeholders with .format() Instead of \'%s\' for String Formatting in Python?

String Formatting in Python: Understanding '%s' Placeholders

When attempting to substitute placeholders like {0} using % formatting, you may encounter the error "TypeError: not all arguments converted during string formatting." This error often occurs due to mismatches between old-style and new-style string formatting methods.

Old-style % formatting uses % codes for formatting, where each value is specified as follows:

<code class="python">'It will cost $%d dollars.' % 95</code>
Copier après la connexion

Multiple values require a tuple:

<code class="python">&quot;'%s' is longer than '%s'&quot; % (name1, name2)</code>
Copier après la connexion

New-style {} formatting, on the other hand, utilizes {} codes and the .format method:

<code class="python">'It will cost ${0} dollars.'.format(95)</code>
Copier après la connexion
<code class="python">&quot;'{0}' is longer than '{1}'&quot;.format(name1, name2)</code>
Copier après la connexion

To fix the error in the provided code, you should use {} placeholders and call the .format method:

<code class="python">print("'{0}' is longer than '{1}'".format(name1, name2))</code>
Copier après la connexion

By following these guidelines, you can ensure proper string formatting and avoid the "TypeError: not all arguments converted during string formatting" error.

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!

source:php
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Derniers articles par auteur
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!