Heim  >  Artikel  >  Backend-Entwicklung  >  So vermeiden Sie „TypeError: Not All Arguments Converted“ bei der Verwendung von Platzhalterformatierung in Python

So vermeiden Sie „TypeError: Not All Arguments Converted“ bei der Verwendung von Platzhalterformatierung in Python

Patricia Arquette
Patricia ArquetteOriginal
2024-10-18 13:04:03942Durchsuche

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.

Das obige ist der detaillierte Inhalt vonSo vermeiden Sie „TypeError: Not All Arguments Converted“ bei der Verwendung von Platzhalterformatierung in Python. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn