>  기사  >  백엔드 개발  >  Python에서 자리 표시자 형식을 사용할 때 \"TypeError: 모든 인수가 변환되지 않음\"을 방지하는 방법

Python에서 자리 표시자 형식을 사용할 때 \"TypeError: 모든 인수가 변환되지 않음\"을 방지하는 방법

Patricia Arquette
Patricia Arquette원래의
2024-10-18 13:04:03941검색

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에서 자리 표시자 형식을 사용할 때 \"TypeError: 모든 인수가 변환되지 않음\"을 방지하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.