在 Python 中使用佔位符格式時如何避免'類型錯誤:未轉換所有參數”

Patricia Arquette
發布: 2024-10-18 13:04:03
原創
947 人瀏覽過

How to Avoid \

TypeError When Substituting Placeholder with % Formatting

When attempting to substitute a placeholder like {0} using % formatting, developers may encounter the following error: "TypeError: not all arguments converted during string formatting." This error stems from improper formatting, specifically due to a mix-up between old-style % formatting and new-style {} formatting.

Old-style % formatting employs placeholders like %d for formatting, as exemplified below:

'It will cost $%d dollars.' % 95
登入後複製

However, when utilizing multiple values, they must be provided as a tuple:

"'%s' is longer than '%s'" % (name1, name2)
登入後複製

On the other hand, new-style {} formatting employs placeholders like {} and the .format method. It's crucial to avoid mixing these two styles. If the template string contains {} placeholders, .format should be used, not %.

# Correct:
'It will cost ${0} dollars.'.format(95)
"'{0}' is longer than '{1}'".format(name1, name2)

# Incorrect (Do not mix % and {}):
'It will cost ${0} dollars.' % 95
"'%0' is longer than '%1'" % (name1, name2)
登入後複製

By adhering to these formatting guidelines, developers can resolve the "TypeError: not all arguments converted during string formatting" error and format their strings correctly.

以上是在 Python 中使用佔位符格式時如何避免'類型錯誤:未轉換所有參數”的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!