Develop

[Python] SyntaxError: f-string: unmatched '[' 원인 및 해결 방법

너드나무 2024. 11. 26. 08:14
반응형

f-string Syntax

2.4.3. f-strings, Python 3.13.0 Docs

Python의 f-string문자열 내에서 변수 등 동적인 값을 표현합니다.

하지만 f-string을 사용할 때 잘못된 구문으로 인해 SyntaxError: f-string: unmatched '['와 같은 에러가 발생할 수 있습니다.
이번 글에서는 이 에러의 원인과 해결 방법을 소개합니다.

이슈 사례 및 원인

  • f-string은 문자열 내부에서 중괄호 {}로 변수를 감싸 표현식을 삽입합니다.
  • 이슈 사례
    • f-string은 표현식 selectors["link_selector"]["selector"]는 f-string 영역을 (")로 지정하였지만,
    • 중괄호 안에 추가적인 큰따옴표(")를 포함하고 있어 Python이 이를 적절히 구문 분석하지 못합니다.
    • f"..." 안에서 selectors["link_selector"]["selector"]의 큰따옴표(")가 f-string의 종료로 잘못 해석될 수 있습니다.
selectors = {
    "link_selector": {
        "selector": "a.link"
    }
}

# f-string 사용 중 SyntaxError 발생
f"select_one: {selectors["link_selector"]["selector"]}"

SyntaxError: f-string: unmatched '['

해결 방법

  1. 외부와 내부 따옴표의 충돌 회피
    • f-string의 외부와 내부에서 사용하는 따옴표가 동일하면 Python이 이를 적절히 해석하지 못합니다.
    • 외부 따옴표내부 따옴표구분하여 사용해야 합니다.
  2. f-string에서 표현식을 명확히 작성
    • f-string은 {} 내부의 표현식을 그대로 평가합니다.
    • 중첩된 표현식에서 따옴표가 충돌하지 않도록 주의해야 합니다.
  3. 예제 코드
    1. f-string의 외부 따옴표 변경
    2. 내부 따옴표 변경
# 외부 따옴표를 작은따옴표로 변경
f'select_one: {selectors["link_selector"]["selector"]}'

# 내부 따옴표를 작은따옴표로 변경
f"select_one: {selectors['link_selector']['selector']}"

select_one: a.link

 

 

2. Lexical analysis

A Python program is read by a parser. Input to the parser is a stream of tokens, generated by the lexical analyzer. This chapter describes how the lexical analyzer breaks a file into tokens. Python...

docs.python.org

728x90
반응형