首页 >后端开发 >Python教程 >在 Python 中,何时应该使用 .format() 中的'{}”占位符而不是'%s”进行字符串格式化?

在 Python 中,何时应该使用 .format() 中的'{}”占位符而不是'%s”进行字符串格式化?

Barbara Streisand
Barbara Streisand原创
2024-10-18 12:54:30846浏览

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 中,何时应该使用 .format() 中的'{}”占位符而不是'%s”进行字符串格式化?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn