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">"'%s' is longer than '%s'" % (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">"'{0}' is longer than '{1}'".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 중국어 웹사이트의 기타 관련 기사를 참조하세요!