Wann sollte ich \'{}\'-Platzhalter mit .format() anstelle von \'%s\' für die String-Formatierung in Python verwenden?

Barbara Streisand
Freigeben: 2024-10-18 12:54:30
Original
723 Leute haben es durchsucht

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>
Nach dem Login kopieren

Multiple values require a tuple:

<code class="python">&quot;'%s' is longer than '%s'&quot; % (name1, name2)</code>
Nach dem Login kopieren

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

<code class="python">'It will cost ${0} dollars.'.format(95)</code>
Nach dem Login kopieren
<code class="python">&quot;'{0}' is longer than '{1}'&quot;.format(name1, name2)</code>
Nach dem Login kopieren

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>
Nach dem Login kopieren

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

Das obige ist der detaillierte Inhalt vonWann sollte ich \'{}\'-Platzhalter mit .format() anstelle von \'%s\' für die String-Formatierung in Python verwenden?. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Quelle:php
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Neueste Artikel des Autors
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!