Rumah > pembangunan bahagian belakang > Tutorial Python > Bagaimana untuk Menyelesaikan Ralat \'TypeError: String Formatting Mismatch\'?

Bagaimana untuk Menyelesaikan Ralat \'TypeError: String Formatting Mismatch\'?

Patricia Arquette
Lepaskan: 2024-10-18 12:08:26
asal
720 orang telah melayarinya

How to Resolve the \

Understanding the TypeError: String Formatting Mismatch

When trying to incorporate placeholders like {0} in string formatting, it's essential to understand the nuances of the formatting method being used. The error message "TypeError: not all arguments converted during string formatting" typically arises when the %-based formatting method is misused.

Old-style % Formatting

The % formatting method employs % codes to specify formatting operations. When formatting a single value, it can be included directly in the string:

<code class="python">'It will cost $%d dollars.' % 95</code>
Salin selepas log masuk

However, for multiple values, a tuple must be provided:

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

New-style {} Formatting

In contrast, the {} formatting method utilizes {} placeholders and the .format() method. It's crucial to avoid mixing these methods. If the "template" string contains {} placeholders, use .format(), not %.

<code class="python"># Values as method arguments
'It will cost ${0} dollars.'.format(95)
&quot;'{0}' is longer than '{1}'&quot;.format(name1, name2)</code>
Salin selepas log masuk

Atas ialah kandungan terperinci Bagaimana untuk Menyelesaikan Ralat \'TypeError: String Formatting Mismatch\'?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Artikel terbaru oleh pengarang
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan