Bilakah Saya Harus Menggunakan \'{}\' Pemegang Tempat dengan .format() Daripada \'%s\' untuk Pemformatan Rentetan dalam Python?

Barbara Streisand
Lepaskan: 2024-10-18 12:54:30
asal
724 orang telah melayarinya

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>
Salin selepas log masuk

Multiple values require a tuple:

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

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

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

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>
Salin selepas log masuk

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

Atas ialah kandungan terperinci Bilakah Saya Harus Menggunakan \'{}\' Pemegang Tempat dengan .format() Daripada \'%s\' untuk Pemformatan Rentetan dalam Python?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

sumber: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
Tentang kita Penafian Sitemap
Laman web PHP Cina:Latihan PHP dalam talian kebajikan awam,Bantu pelajar PHP berkembang dengan cepat!