[Python] format 함수 에러 SyntaxError: positional argument follows keyword argument

파이썬 format 함수 사용 시 발생하는 positional argument follows keyword argument 에러의 발생 이유에 대해 다룹니다.
ludvico el's avatar
Apr 21, 2024
[Python] format 함수 에러 SyntaxError: positional argument follows keyword argument
#1. 숫자 포매팅 >>> "I eat {0} apples.".format(3) 'I eat 3 apples.' >>> "I eat {0} apples." 'I eat {0} apples.' #당연하게도 {}에 .format을 사용하지 않으면 #그대로 출력된다. >>> a = 1 >>> "I eat {0} apples.".format(a) 'I eat 1 apples.' #변수도 포맷팅 가능한 모습. "I eat {2} apples.".format(a) Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: Replacement index 2 out of range for positional args tuple #{}사이에는 0부터 시작하며 넣어야 한다. #첫 {}에는 0, 그 다음 {}에는 1, 2, ...
#2. 문자열 포매팅 >>> "I eat {0} apples." .format("five") 'I eat five apples.'
#3. 2개 이상의 값 넣기(직접) "I eat {0} {1}." .format(3, "bananas") 'I eat 3 bananas.' #4. 2개 이상의 값 넣기(변수) "I eat {0} {1}." .format(number, fruit) 'I eat 10 mangoes.'
#5. {name}으로 넣기 >>> "I ate {number} apples. so I was sick {day} days." .format(number = 6, day = 3) 'I ate 6 apples. so I was sick 3 days.' #{name}으로 포매팅 시, #반드시 name = value와 같은 입력값 필요.
#6. 인덱스와 이름을 혼용해서 넣기 >>> "I ate {0} apples. so I was sick for {day} days." .format(5, day = 10) 'I ate 5 apples. so I was sick for 10 days.' >>> "I ate {number} apples. so I was sick for {0} days." .format(3, number = 3) 'I ate 3 apples. so I was sick for 3 days.' ##아래에서 문제 발생 >>> "I ate {number} apples. so I was sick for {0} days." .format(number = 3, 5) File "<stdin>", line 1 "I ate {number} apples. so I was sick for {0} days." .format(number = 3, 5) ^ SyntaxError: positional argument follows keyword argument #위 문제는 다음과 같이 발생하는 것으로 추정. #{0}, {1} 등의 인덱스 포매팅은 #포매팅 밸류를 .format(인덱스밸류1, 인덱스밸류2, 네임밸류2) #이렇게 있을 때, #무조건 {0}의 밸류는 .format()의 첫 번째에 #무조건 {1}의 밸류는 .format()의 두 번째에 #있어야 되는 것으로 추정된다. 즉, #문자열 내에서 순서가 {0}, {name1}, {1}, {name2}, {2} #이렇게 있어도 아래와 같이 하지말고, #.format{index1, name1 = a, index2, name2 = b, index3) #아래와 같이 해야되는 것으로 추정된다. #.format{index1, index2, index3, name1 = a, name2 = b) #(단, 여기서 name1과 name2는 따로 지정해주므로 둘의 순서는 상관 없을 것으로 추정됨.) #아래에서 검증해본다.
#6에 대한 검증 >>> "I have {0} apples. Hi, {name}. I was sick for {1} days. i'm in {country} now. You have {2} pineapples." .format(5, 2, 10, name = "John", country = "SouthKorea") "I have 5 apples. Hi, John. I was sick for 2 days. i'm in SouthKorea now. You have 10 pineapples." #성공 >>> "I have {0} apples. Hi, {name}. I was sick for {1} days. i'm in {country} now. You have {2} pineapples." .format(5, 2, 10, country = "SouthKorea", name = "John") "I have 5 apples. Hi, John. I was sick for 2 days. i'm in SouthKorea now. You have 10 pineapples." #성공
 
 
 
Share article

rudevico