ERROR

[format] ValueError: cannot switch from manual field specification to automatic field numbering

파송송 2023. 2. 10. 15:24
728x90

비슷한 에러 : ValueError: cannot switch from automatic field numbering to manual field specification

python format을 사용할 때 발생할 수 있는 에러이다.

print('{}{}{1}'.format('1','2','3'))


format 사용법

이는 format 자릿수 때문인데 format을 사용할 때 2가지 방법으로 사용할 수 있다.

print('{}{}{}'.format('1','2','3'))

print('{}{}{}{}'.format('1','2','3'))

{}의 개수와 파라미터 개수가 같아야하며 다르면 위와 같은 에러가 발생한다.


print('{2}{0}{1}'.format('1','2','3'))

위는 자리수를자릿수를 지정해주지 않고 들어온 순서대로 쓰는 방법이고 아래는 자릿수를 지정하여 변수를 재사용할 수 있다. 이 경우에는 파라미터 개수와 {}의 개수가 달라도 상관없다.

print('{2}{0}{1}{0}'.format('1','2','3'))


해결

이 2가지 방법은 혼합하여 사용할 수 없고 번호를 지정해주던가 지정하지 말고 사용해야 한다.

print('{}{}{1}{}'.format('1','2','3'))

ValueError: cannot switch from automatic field numbering to manual field specification

다음과 같이 혼합하여 사용하면 위의 에러가 발생한다.

728x90