ホームページ  >  記事  >  バックエンド開発  >  Python で文字列の書式設定に「%s」の代わりに .format() で「{}」プレースホルダを使用する必要があるのはどのような場合ですか?

Python で文字列の書式設定に「%s」の代わりに .format() で「{}」プレースホルダを使用する必要があるのはどのような場合ですか?

Barbara Streisand
Barbara Streisandオリジナル
2024-10-18 12:54:30716ブラウズ

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>

Multiple values require a tuple:

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

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

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

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>

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

以上がPython で文字列の書式設定に「%s」の代わりに .format() で「{}」プレースホルダを使用する必要があるのはどのような場合ですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。