찾다
백엔드 개발파이썬 튜토리얼%와 {} 자리 표시자를 혼합할 때 문자열 형식 오류를 수정하는 방법은 무엇입니까?

How to Correct String Formatting Error When Mixing % and {} Placeholders?

Error in String Formatting Using % and {}

While attempting to format strings using placeholders like {0}, you may encounter the error "TypeError: not all arguments converted during string formatting." This error arises due to a misunderstanding of the syntax differences between old-style % formatting and new-style {} formatting.

Old-Style % Formatting

The old-style % formatting technique employs placeholder codes% to format strings. For single values, they can be written as is:

'It will cost $%d dollars.' % 95

For multiple values, they must be supplied as a tuple:

"'%s' is longer than '%s'" % (name1, name2)

New-Style {} Formatting

The new-style {} formatting uses placeholder codes {} and the .format method. Here's the key difference: you cannot mix and match the two styles. If the "template" string contains {} placeholders, then call .format, don't use %.

'It will cost ${0} dollars.'.format(95)

"'{0}' is longer than '{1}'".format(name1, name2)

Correcting the Code

To address the error in the given code, you can either use % formatting consistently or switch to {} formatting:

Old-style % Formatting

print ("'{0}' is longer than '{1}'"% (name1, name2))

New-style {} Formatting

print ("'{0}' is longer than '{1}'".format(name1, name2))

위 내용은 %와 {} 자리 표시자를 혼합할 때 문자열 형식 오류를 수정하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

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

Pythonusesahybridmodelofilationandlostretation : 1) ThePyThoninterPretreCeterCompileSsourcodeIntOplatform-IndependentBecode.

Python은 해석 된 또는 편집 된 언어입니까? 왜 중요한가?Python은 해석 된 또는 편집 된 언어입니까? 왜 중요한가?May 12, 2025 am 12:09 AM

Pythonisbothingretedandcompiled.1) 1) it 'scompiledtobytecodeforportabilityacrossplatforms.2) thebytecodeisthentenningreted, withfordiNamictyTeNgreted, WhithItmayBowerShiledlanguges.

파이썬에서 루프를 사용하여 목록을 연결할 수 있습니까?파이썬에서 루프를 사용하여 목록을 연결할 수 있습니까?May 10, 2025 am 12:14 AM

예, youcanconcatenatelistsusingaloopinpython.1) useeparateloopsforeachlisttoAppenditemStoAresultlist.2) USEANESTEDLOOPTOINTERATEREATERVUNTIPLELISTSFORAMORECOCISOPPOACH.3) ApplyDingConcatenation, likefilterningevennumbers

Concatenate는 Python을 사용합니다 : 사용, Extend () 등Concatenate는 Python을 사용합니다 : 사용, Extend () 등May 10, 2025 am 12:12 AM

themostefficientmethodsforconcatenatinglistsinpythonare : 1) theextend () methodforin-placemodification, 2) itertools.chain () formemoryefficiencywithlargedatasets.theextend () methodModifiestHeoriginAllist, MakingItMemory-effectrequiretcautionsucution

파이썬 루프 : 예와 모범 사례파이썬 루프 : 예와 모범 사례May 10, 2025 am 12:05 AM

Pythonloopsincludeforandforandwhilleoops, withforloopsidealfor and with with with withlopsidealforcections and whileleloopsforcondition basedrepetition.bestpracticesinvolve : 1) 사용 listcomprehensionsforsimpletransformations, 2) forindex-valuepairs, 3) optingforrangeoverlistsformemor를 사용합니다

Python의 실행 모델 : 컴파일, 해석 또는 둘 다?Python의 실행 모델 : 컴파일, 해석 또는 둘 다?May 10, 2025 am 12:04 AM

pythonisbothcompiledandlandingreted.

Python은 라인별로 실행됩니까?Python은 라인별로 실행됩니까?May 10, 2025 am 12:03 AM

Python은 엄격하게 라인 별 실행이 아니지만 통역사 메커니즘을 기반으로 최적화되고 조건부 실행입니다. 통역사는 코드를 PVM에 의해 실행 된 바이트 코드로 변환하며 상수 표현식을 사전 컴파일하거나 루프를 최적화 할 수 있습니다. 이러한 메커니즘을 이해하면 코드를 최적화하고 효율성을 향상시키는 데 도움이됩니다.

파이썬에서 두 목록을 연결하는 대안은 무엇입니까?파이썬에서 두 목록을 연결하는 대안은 무엇입니까?May 09, 2025 am 12:16 AM

Python에는 두 개의 목록을 연결하는 방법이 많이 있습니다. 1. 연산자 사용 간단하지만 큰 목록에서는 비효율적입니다. 2. 효율적이지만 원래 목록을 수정하는 확장 방법을 사용하십시오. 3. 효율적이고 읽기 쉬운 = 연산자를 사용하십시오. 4. 메모리 효율적이지만 추가 가져 오기가 필요한 itertools.chain function을 사용하십시오. 5. 우아하지만 너무 복잡 할 수있는 목록 구문 분석을 사용하십시오. 선택 방법은 코드 컨텍스트 및 요구 사항을 기반으로해야합니다.

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

에디트플러스 중국어 크랙 버전

에디트플러스 중국어 크랙 버전

작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음

MinGW - Windows용 미니멀리스트 GNU

MinGW - Windows용 미니멀리스트 GNU

이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.

ZendStudio 13.5.1 맥

ZendStudio 13.5.1 맥

강력한 PHP 통합 개발 환경