ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Python/Reference/어휘분석
    코딩/Python 2024. 3. 15. 14:47
    728x90

    파이썬을 사용하면서 파이썬 매뉴얼을 참고해야 할 경우가 있다. 이럴 경우 매뉴얼의 구성과 용어에 대해 알고 접근하는 것이 도움이 된다.

    그래서 매뉴얼을 설명하는 챕터 1과 2를 번역해 올린다.

    원문은 아래 링크 참조

    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 reads program text as Unicode code points; the encoding of a source file can be given by an encoding declaration and defaults to UTF-8, see PEP 3120 for details. If the source file cannot be decoded, a SyntaxError is raised.

    Python 프로그램은 파서에 의해 읽혀진다. 파서에 대한 입력은 어휘 분석기에 의해 생성된 토큰 스트림이다. 이 장에서는 어휘 분석기가 파일을 토큰으로 나누는 방법을 설명한다.

    Python은 프로그램 텍스트를 유니코드 코드 포인트로 읽는다. 소스 파일의 인코딩은 인코딩 선언으로 제공될 수 있으며 기본값은 UTF-8이다. 자세한 내용은 PEP 3120을 참조한다. 소스 파일을 디코딩할 수 없으면 SyntaxError가 발생한다.

    2.1. Line structure

    A Python program is divided into a number of logical lines.

    Python 프로그램은 여러 개의 논리적 행으로 나뉜다.

    2.1.1. Logical lines

    The end of a logical line is represented by the token NEWLINE. Statements cannot cross logical line boundaries except where NEWLINE is allowed by the syntax (e.g., between statements in compound statements). A logical line is constructed from one or more physical lines by following the explicit or implicit line joining rules.

    논리적 줄의 끝은 NEWLINE 토큰으로 표시된다. 구문에서 NEWLINE이 허용되는 경우를 제외하고 명령문은 논리적 줄 경계를 넘을 수 없다(예: 복합 명령문의 명령문 사이). 논리적 라인은 명시적 또는 암시적 라인 조인 규칙을 따라 하나 이상의 물리적 라인으로 구성된다.

    2.1.2. Physical lines

    A physical line is a sequence of characters terminated by an end-of-line sequence. In source files and strings, any of the standard platform line termination sequences can be used - the Unix form using ASCII LF (linefeed), the Windows form using the ASCII sequence CR LF (return followed by linefeed), or the old Macintosh form using the ASCII CR (return) character. All of these forms can be used equally, regardless of platform. The end of input also serves as an implicit terminator for the final physical line.

    When embedding Python, source code strings should be passed to Python APIs using the standard C conventions for newline characters (the \n character, representing ASCII LF, is the line terminator).

    물리적 줄은 줄 끝 시퀀스로 끝나는 일련의 문자다. 소스 파일 및 문자열에서는 표준 플랫폼 줄 종료 시퀀스 중 하나를 사용할 수 있다. 즉, ASCII LF(줄 바꿈)를 사용하는 Unix 형식, ASCII 시퀀스 CR LF(반환 다음에 줄 바꿈)를 사용하는 Windows 형식 또는 ASCII CR(반환) 문자를 사용하는 이전 Macintosh 형식을 사용할 수 있다. 이러한 모든 양식은 플랫폼에 관계없이 동일하게 사용할 수 있다. 입력의 끝은 최종 물리적 라인에 대한 암시적 종결자 역할도 한다.

    Python을 포함할 때 소스 코드 문자열은 개행 문자에 대한 표준 C 규칙을 사용하여 Python API에 전달되어야 한다(ASCII LF를 나타내는 \n 문자는 줄 종결자이다).

    728x90

    2.1.3. Comments

    A comment starts with a hash character (#) that is not part of a string literal, and ends at the end of the physical line. A comment signifies the end of the logical line unless the implicit line joining rules are invoked. Comments are ignored by the syntax.

    주석은 문자열 리터럴의 일부가 아닌 해시 문자(#)로 시작하고 실제 줄의 끝에서 끝난다. 주석은 암시적 줄 결합 규칙이 호출되지 않는 한 논리적 줄의 끝을 나타낸다. 주석은 구문에 의해 무시된다.

    2.1.4. Encoding declarations

    If a comment in the first or second line of the Python script matches the regular expression coding[=:]\s*([-\w.]+), this comment is processed as an encoding declaration; the first group of this expression names the encoding of the source code file. The encoding declaration must appear on a line of its own. If it is the second line, the first line must also be a comment-only line. The recommended forms of an encoding expression are

    Python 스크립트의 첫 번째 또는 두 번째 줄에 있는 주석이 정규식 coding[=:]\s*([-\w.]+)와 일치하는 경우 이 주석은 인코딩 선언으로 처리된다. 이 표현식의 첫 번째 그룹은 소스 코드 파일의 인코딩 이름을 지정한다. 인코딩 선언은 자체 줄에 나타나야 한다. 두 번째 줄인 경우 첫 번째 줄도 주석 전용 줄이어야 한다. 인코딩 표현식의 권장 형식은 다음과 같다.

    # -*- coding: <encoding-name> -*-

     

    which is recognized also by GNU Emacs, and

    이는 GNU Emacs에서도 인식된다.

    # vim:fileencoding=<encoding-name>

     

    which is recognized by Bram Moolenaar’s VIM.

    If no encoding declaration is found, the default encoding is UTF-8. In addition, if the first bytes of the file are the UTF-8 byte-order mark (b'\xef\xbb\xbf'), the declared file encoding is UTF-8 (this is supported, among others, by Microsoft’s notepad).

    If an encoding is declared, the encoding name must be recognized by Python (see Standard Encodings). The encoding is used for all lexical analysis, including string literals, comments and identifiers.

    이는 Bram Moolenaar의 VIM에 의해 인식된다.

    인코딩 선언이 없으면 기본 인코딩은 UTF-8이다. 또한 파일의 첫 번째 바이트가 UTF-8 바이트 순서 표시(b'\xef\xbb\xbf')인 경우 선언된 파일 인코딩은 UTF-8이다(이는 특히 Microsoft 메모장에서 지원된다).

    인코딩이 선언되면 Python에서 인코딩 이름을 인식해야 한다(표준 인코딩 참조). 인코딩은 문자열 리터럴, 주석 및 식별자를 포함한 모든 어휘 분석에 사용된다.

    2.1.5. Explicit line joining

    Two or more physical lines may be joined into logical lines using backslash characters (\), as follows: when a physical line ends in a backslash that is not part of a string literal or comment, it is joined with the following forming a single logical line, deleting the backslash and the following end-of-line character. For example:

    두 개 이상의 물리적 줄은 다음과 같이 백슬래시 문자(\)를 사용하여 논리적 줄로 결합될 수 있다. 물리적 줄이 문자열 리터럴이나 주석의 일부가 아닌 백슬래시로 끝나는 경우 다음과 결합되어 단일 논리적 라인을 형성한다. 백슬래시와 다음 줄 끝 문자를 삭제한다. 예를 들어:

    if 1900 < year < 2100 and 1 <= month <= 12 \
       and 1 <= day <= 31 and 0 <= hour < 24 \
       and 0 <= minute < 60 and 0 <= second < 60:   # Looks like a valid date
            return 1

     

    A line ending in a backslash cannot carry a comment. A backslash does not continue a comment. A backslash does not continue a token except for string literals (i.e., tokens other than string literals cannot be split across physical lines using a backslash). A backslash is illegal elsewhere on a line outside a string literal.

    백슬래시로 끝나는 줄에는 주석을 포함할 수 없다. 백슬래시는 주석을 계속하지 않는다. 백슬래시는 문자열 리터럴을 제외하고 토큰을 계속하지 않는다. 즉, 문자열 리터럴 이외의 토큰은 백슬래시를 사용하여 물리적 줄에 걸쳐 분할할 수 없다. 백슬래시는 문자열 리터럴 외부 줄의 다른 곳에서는 사용할 수 없다.

    2.1.6. Implicit line joining

    Expressions in parentheses, square brackets or curly braces can be split over more than one physical line without using backslashes. For example:

    괄호, 대괄호 또는 중괄호 안의 표현식은 백슬래시를 사용하지 않고도 둘 이상의 실제 행으로 분할될 수 있다. 예를 들어:

    month_names = ['Januari', 'Februari', 'Maart',      # These are the
                   'April',   'Mei',      'Juni',       # Dutch names
                   'Juli',    'Augustus', 'September',  # for the months
                   'Oktober', 'November', 'December']   # of the year

     

    Implicitly continued lines can carry comments. The indentation of the continuation lines is not important. Blank continuation lines are allowed. There is no NEWLINE token between implicit continuation lines. Implicitly continued lines can also occur within triple-quoted strings (see below); in that case they cannot carry comments.

    암시적으로 연속된 줄에는 주석이 포함될 수 있다. 연속된 줄의 들여쓰기는 중요하지 않다. 빈 연속 줄이 허용된다. 암시적 연속 줄 사이에는 NEWLINE 토큰이 없다. 암시적으로 연속된 줄은 삼중따옴표로 묶인 문자열 내에서도 나타날 수 있다(아래 참조). 이 경우 코멘트를 전달할 수 없다.

    2.1.7. Blank lines

    A logical line that contains only spaces, tabs, formfeeds and possibly a comment, is ignored (i.e., no NEWLINE token is generated). During interactive input of statements, handling of a blank line may differ depending on the implementation of the read-eval-print loop. In the standard interactive interpreter, an entirely blank logical line (i.e. one containing not even whitespace or a comment) terminates a multi-line statement.

    공백, 탭, 폼피드 및 주석만 포함된 논리적 줄은 무시된다(즉, NEWLINE 토큰이 생성되지 않음). 명령문을 대화식으로 입력하는 동안 빈 줄 처리는 읽기-평가-인쇄 루프의 구현에 따라 다를 수 있다. 표준 대화형 인터프리터에서는 완전히 비어 있는 논리적 줄(즉, 공백이나 주석도 포함하지 않은 줄)이 여러 줄 문을 종료한다.

    2.1.8. Indentation

    Leading whitespace (spaces and tabs) at the beginning of a logical line is used to compute the indentation level of the line, which in turn is used to determine the grouping of statements.

    Tabs are replaced (from left to right) by one to eight spaces such that the total number of characters up to and including the replacement is a multiple of eight (this is intended to be the same rule as used by Unix). The total number of spaces preceding the first non-blank character then determines the line’s indentation. Indentation cannot be split over multiple physical lines using backslashes; the whitespace up to the first backslash determines the indentation.

    Indentation is rejected as inconsistent if a source file mixes tabs and spaces in a way that makes the meaning dependent on the worth of a tab in spaces; a TabError is raised in that case.

    Cross-platform compatibility note: because of the nature of text editors on non-UNIX platforms, it is unwise to use a mixture of spaces and tabs for the indentation in a single source file. It should also be noted that different platforms may explicitly limit the maximum indentation level.

    A formfeed character may be present at the start of the line; it will be ignored for the indentation calculations above. Formfeed characters occurring elsewhere in the leading whitespace have an undefined effect (for instance, they may reset the space count to zero).

    The indentation levels of consecutive lines are used to generate INDENT and DEDENT tokens, using a stack, as follows.

    Before the first line of the file is read, a single zero is pushed on the stack; this will never be popped off again. The numbers pushed on the stack will always be strictly increasing from bottom to top. At the beginning of each logical line, the line’s indentation level is compared to the top of the stack. If it is equal, nothing happens. If it is larger, it is pushed on the stack, and one INDENT token is generated. If it is smaller, it must be one of the numbers occurring on the stack; all numbers on the stack that are larger are popped off, and for each number popped off a DEDENT token is generated. At the end of the file, a DEDENT token is generated for each number remaining on the stack that is larger than zero.

    Here is an example of a correctly (though confusingly) indented piece of Python code:

    논리 줄 시작 부분의 선행 공백(공백 및 탭)은 줄의 들여쓰기 수준을 계산하는 데 사용되며, 이는 차례로 명령문 그룹을 결정하는 데 사용된다.

    탭은 왼쪽에서 오른쪽으로 1~8개의 공백으로 대체되어 대체 문자를 포함한 최대 문자 수가 8의 배수가 된다(이는 Unix에서 사용되는 것과 동일한 규칙을 따른다). 공백이 아닌 첫 번째 문자 앞의 총 공백 수에 따라 줄의 들여쓰기가 결정된다. 백슬래시를 사용하여 들여쓰기를 여러 실제 줄로 분할할 수 없다. 첫 번째 백슬래시까지의 공백이 들여쓰기를 결정한다.

    공백에 있는 탭의 가치에 따라 의미가 달라지는 방식으로 소스 파일이 탭과 공백을 혼합하는 경우 들여쓰기는 일관성이 없는 것으로 거부된다. 이 경우 TabError가 발생한다.

    플랫폼 간 호환성 참고 사항: UNIX가 아닌 플랫폼의 텍스트 편집기 특성으로 인해 단일 소스 파일의 들여쓰기에 공백과 탭을 혼합하여 사용하는 것은 현명하지 않다. 또한 플랫폼에 따라 최대 들여쓰기 수준이 명시적으로 제한될 수 있다는 점에 유의해야 한다.

    행 시작 부분에 폼피드 문자가 있을 수 있다. 위의 들여쓰기 계산에서는 무시된다. 선행 공백의 다른 곳에서 발생하는 폼피드 문자는 정의되지 않은 효과를 갖는다(예를 들어 공백 수를 0으로 재설정할 수 있음).

    연속된 줄의 들여쓰기 수준은 다음과 같이 스택을 사용하여 INDENT 및 DEDENT 토큰을 생성하는 데 사용된다.

    파일의 첫 번째 줄을 읽기 전에 단일 0이 스택에 푸시된다. 이것은 다시 제거되지 않을 것이다. 스택에 푸시된 숫자는 항상 아래에서 위로 엄격하게 증가한다. 각 논리 줄의 시작 부분에서 줄의 들여쓰기 수준이 스택의 맨 위와 비교된다. 동일하면 아무 일도 일어나지 않는다. 그보다 크면 스택에 푸시되고 하나의 INDENT 토큰이 생성된다. 더 작은 경우 스택에 있는 숫자 중 하나여야 한다. 스택에서 더 큰 숫자는 모두 팝되고, 팝된 각 숫자에 대해 DEDENT 토큰이 생성된다. 파일 끝에서 0보다 큰 스택에 남아 있는 각 숫자에 대해 DEDENT 토큰이 생성된다.

    다음은 올바르게 (혼란스럽기는 하지만) 들여쓰기된 Python 코드의 예이다:

    def perm(l):
            # Compute the list of all permutations of l
        if len(l) <= 1:
                      return [l]
        r = []
        for i in range(len(l)):
                 s = l[:i] + l[i+1:]
                 p = perm(s)
                 for x in p:
                  r.append(l[i:i+1] + x)
        return r

     

    The following example shows various indentation errors:

    다음 예에서는 다양한 들여쓰기 오류를 보여준다.

     def perm(l):                       # error: first line indented
    for i in range(len(l)):             # error: not indented
        s = l[:i] + l[i+1:]
            p = perm(l[:i] + l[i+1:])   # error: unexpected indent
            for x in p:
                    r.append(l[i:i+1] + x)
                return r                # error: inconsistent dedent

     

    (Actually, the first three errors are detected by the parser; only the last error is found by the lexical analyzer — the indentation of return r does not match a level popped off the stack.)

    (실제로 처음 세 개의 오류는 파서에 의해 감지된다. 어휘 분석기는 마지막 오류만 발견한다. return r의 들여쓰기는 스택에서 팝된 레벨과 일치하지 않는다.)

    2.1.9. Whitespace between tokens

    Except at the beginning of a logical line or in string literals, the whitespace characters space, tab and formfeed can be used interchangeably to separate tokens. Whitespace is needed between two tokens only if their concatenation could otherwise be interpreted as a different token (e.g., ab is one token, but a b is two tokens).

     

    논리적 줄의 시작 부분이나 문자열 리터럴을 제외하고 공백 문자 공백, 탭 및 폼피드는 토큰을 구분하기 위해 교대로 사용할 수 있다. 연결이 다른 토큰으로 해석될 수 있는 경우에만 두 토큰 사이에 공백이 필요하다(예: ab는 하나의 토큰이지만 a b는 두 개의 토큰이다).

    2.2. Other tokens

    Besides NEWLINE, INDENT and DEDENT, the following categories of tokens exist: identifiers, keywords, literals, operators, and delimiters. Whitespace characters (other than line terminators, discussed earlier) are not tokens, but serve to delimit tokens. Where ambiguity exists, a token comprises the longest possible string that forms a legal token, when read from left to right.

    NEWLINE, INDENT 및 DEDENT 외에도 식별자, 키워드, 리터럴, 연산자 및 구분 기호와 같은 토큰 범주가 존재한다. 공백 문자(앞서 설명한 줄 종결자 제외)는 토큰이 아니지만 토큰을 구분하는 역할을 한다. 모호성이 존재하는 경우 토큰은 왼쪽에서 오른쪽으로 읽을 때 합법적인 토큰을 형성하는 가능한 가장 긴 문자열로 구성된다.

    2.3. Identifiers and keywords

    Identifiers (also referred to as names) are described by the following lexical definitions.

    The syntax of identifiers in Python is based on the Unicode standard annex UAX-31, with elaboration and changes as defined below; see also PEP 3131 for further details.

    Within the ASCII range (U+0001..U+007F), the valid characters for identifiers are the same as in Python 2.x: the uppercase and lowercase letters A through Z, the underscore _ and, except for the first character, the digits 0 through 9.

    Python 3.0 introduces additional characters from outside the ASCII range (see PEP 3131). For these characters, the classification uses the version of the Unicode Character Database as included in the unicodedata module.

    Identifiers are unlimited in length. Case is significant.

    식별자(이름이라고도 함)는 다음 어휘 정의로 설명된다.

    Python의 식별자 구문은 유니코드 표준 부록 UAX-31을 기반으로 하며 아래 정의된 대로 세심하게 변경되었다. 자세한 내용은 PEP 3131을 참조한다.

    ASCII 범위(U+0001..U+007F) 내에서 식별자에 유효한 문자는 Python 2.x와 동일하다: 대문자 및 소문자 A부터 Z까지, 밑줄 _ 및 첫 번째 문자를 제외하고 숫자 0부터 9까지.

    Python 3.0에는 ASCII 범위 외부의 추가 문자가 도입되었다(PEP 3131 참조). 이러한 문자의 경우 분류에서는 unicodedata 모듈에 포함된 유니코드 문자 데이터베이스 버전을 사용한다.

    식별자의 길이에는 제한이 없다. 대소문자가 중요하다.

    identifier   ::=  xid_start xid_continue*
    id_start     ::=  <all characters in general categories Lu, Ll, Lt, Lm, Lo, Nl, the underscore, and characters with the Other_ID_Start property>
    id_continue  ::=  <all characters in id_start, plus characters in the categories Mn, Mc, Nd, Pc and others with the Other_ID_Continue property>
    xid_start    ::=  <all characters in id_start whose NFKC normalization is in "id_start xid_continue*">
    xid_continue ::=  <all characters in id_continue whose NFKC normalization is in "id_continue*">

     

    The Unicode category codes mentioned above stand for:

    위에 언급된 유니코드 범주 코드는 다음을 의미한다.

     

    • Lu - uppercase letters
    • Ll - lowercase letters
    • Lt - titlecase letters
    • Lm - modifier letters
    • Lo - other letters
    • Nl - letter numbers
    • Mn - nonspacing marks
    • Mc - spacing combining marks
    • Nd - decimal numbers
    • Pc - connector punctuations
    • Other_ID_Start - explicit list of characters in PropList.txt to support backwards compatibility
    • Other_ID_Continue - likewise

     

    • Lu - 대문자
    • Ll - 소문자
    • Lt - 제목 문자
    • Lm - 수정자 문자
    • Lo - 다른 글자
    • Nl - 문자 숫자
    • Mn - 간격 없음 표시
    • Mc - 간격 결합 표시
    • Nd - 십진수
    • PC - 커넥터 구두점
    • Other_ID_Start - 이전 버전과의 호환성을 지원하기 위한 PropList.txt의 명시적인 문자 목록
    • Other_ID_Continue - 마찬가지

    All identifiers are converted into the normal form NFKC while parsing; comparison of identifiers is based on NFKC.

    A non-normative HTML file listing all valid identifier characters for Unicode 15.0.0 can be found at https://www.unicode.org/Public/15.0.0/ucd/DerivedCoreProperties.txt

    모든 식별자는 구문 분석 중에 일반 형식 NFKC로 변환된다. 식별자 비교는 NFKC를 기반으로 한다.

    유니코드 15.0.0에 대한 모든 유효한 식별자 문자를 나열하는 비표준 HTML 파일은 https://www.unicode.org/Public/15.0.0/ucd/DerivedCoreProperties.txt에서 찾을 수 있다.

    2.3.1. Keywords

    The following identifiers are used as reserved words, or keywords of the language, and cannot be used as ordinary identifiers. They must be spelled exactly as written here:

    다음 식별자는 예약어나 언어의 키워드로 사용되며 일반 식별자로 사용할 수 없다. 여기에 적힌 대로 정확하게 철자를 입력해야 한다.

    False      await      else       import     pass
    None       break      except     in         raise
    True       class      finally    is         return
    and        continue   for        lambda     try
    as         def        from       nonlocal   while
    assert     del        global     not        with
    async      elif       if         or         yield

    2.3.2. Soft Keywords

    New in version 3.10.

    Some identifiers are only reserved under specific contexts. These are known as soft keywords. The identifiers match, case, type and _ can syntactically act as keywords in certain contexts, but this distinction is done at the parser level, not when tokenizing.

    As soft keywords, their use in the grammar is possible while still preserving compatibility with existing code that uses these names as identifier names.

    match, case, and _ are used in the match statement. type is used in the type statement.

    Changed in version 3.12: type is now a soft keyword.

    버전 3.10의 새로운 기능이다.

    일부 식별자는 특정 컨텍스트에서만 예약된다. 이를 소프트 키워드라고 한다. 식별자 match, case, type 및 _는 구문상 특정 컨텍스트에서 키워드로 작동할 수 있지만 이러한 구별은 토큰화할 때가 아닌 파서 수준에서 수행된다.

    소프트 키워드로서 이러한 이름을 식별자 이름으로 사용하는 기존 코드와의 호환성을 유지하면서 문법에서 사용할 수 있다.

    match 문에는 match, case 및 _가 사용된다. type은 type 문에 사용된다.

    버전 3.12에서 변경: type은 이제 소프트 키워드이다.

    2.3.3. Reserved classes of identifiers

    Certain classes of identifiers (besides keywords) have special meanings. These classes are identified by the patterns of leading and trailing underscore characters:

    특정 클래스의 식별자(키워드 제외)에는 특별한 의미가 있다. 이러한 클래스는 선행 및 후행 밑줄 문자의 패턴으로 식별된다.

     

    _*

    Not imported by from module import *.

    from module import *로 가져오지 않는다.

     

    _

    In a case pattern within a match statement, _ is a soft keyword that denotes a wildcard.

    match 문 내의 케이스 패턴에서 _는 와일드카드를 나타내는 소프트 키워드이다.

     

    Separately, the interactive interpreter makes the result of the last evaluation available in the variable _. (It is stored in the builtins module, alongside built-in functions like print.)

    Elsewhere, _ is a regular identifier. It is often used to name “special” items, but it is not special to Python itself.

    이와 별도로 대화형 인터프리터는 마지막 평가 결과를 변수 _에 제공한다. (인쇄와 같은 내장 기능과 함께 내장 모듈에 저장된다.)

    다른 곳에서는 _가 일반 식별자이다. "특별한" 항목의 이름을 지정하는 데 자주 사용되지만 Python 자체에는 특별하지 않다.

    Note

    The name _ is often used in conjunction with internationalization; refer to the documentation for the gettext module for more information on this convention.

    It is also commonly used for unused variables.

    이름 _은 국제화와 함께 사용되는 경우가 많다. 이 규칙에 대한 자세한 내용은 gettext 모듈에 대한 설명서를 참조한다.

    사용되지 않는 변수에도 일반적으로 사용된다.

     

    __*__

    System-defined names, informally known as “dunder” names. These names are defined by the interpreter and its implementation (including the standard library). Current system names are discussed in the Special method names section and elsewhere. More will likely be defined in future versions of Python. Any use of __*__ names, in any context, that does not follow explicitly documented use, is subject to breakage without warning.

    비공식적으로 "dunder" 이름으로 알려진 시스템 정의 이름이다. 이러한 이름은 인터프리터와 그 구현(표준 라이브러리 포함)에 의해 정의된다. 현재 시스템 이름은 특수 메소드 이름 섹션과 다른 곳에서 논의된다. Python의 향후 버전에서는 더 많은 내용이 정의될 가능성이 높다. 어떤 상황에서든 명시적으로 문서화된 사용을 따르지 않고 __*__ 이름을 사용하면 경고 없이 손상될 수 있다.

     

    __*

    Class-private names. Names in this category, when used within the context of a class definition, are re-written to use a mangled form to help avoid name clashes between “private” attributes of base and derived classes. See section Identifiers (Names).

    Class-private 이름. 이 범주의 이름은 클래스 정의 컨텍스트 내에서 사용될 때 기본 클래스와 파생 클래스의 “private” 특성 간의 이름 충돌을 방지하기 위해 잘못된 형식을 사용하도록 다시 작성된다. 식별자(이름) 섹션을 참조한다.

    2.4. Literals

    Literals are notations for constant values of some built-in types.

    리터럴은 일부 내장 유형의 상수 값에 대한 표기법이다.

    2.4.1. String and Bytes literals

    String literals are described by the following lexical definitions:

    문자열 리터럴은 다음 어휘 정의로 설명된다.

    stringliteral   ::=  [stringprefix](shortstring | longstring)
    stringprefix    ::=  "r" | "u" | "R" | "U" | "f" | "F"
                         | "fr" | "Fr" | "fR" | "FR" | "rf" | "rF" | "Rf" | "RF"
    shortstring     ::=  "'" shortstringitem* "'" | '"' shortstringitem* '"'
    longstring      ::=  "'''" longstringitem* "'''" | '"""' longstringitem* '"""'
    shortstringitem ::=  shortstringchar | stringescapeseq
    longstringitem  ::=  longstringchar | stringescapeseq
    shortstringchar ::=  <any source character except "\" or newline or the quote>
    longstringchar  ::=  <any source character except "\">
    stringescapeseq ::=  "\" <any source character>
    bytesliteral   ::=  bytesprefix(shortbytes | longbytes)
    bytesprefix    ::=  "b" | "B" | "br" | "Br" | "bR" | "BR" | "rb" | "rB" | "Rb" | "RB"
    shortbytes     ::=  "'" shortbytesitem* "'" | '"' shortbytesitem* '"'
    longbytes      ::=  "'''" longbytesitem* "'''" | '"""' longbytesitem* '"""'
    shortbytesitem ::=  shortbyteschar | bytesescapeseq
    longbytesitem  ::=  longbyteschar | bytesescapeseq
    shortbyteschar ::=  <any ASCII character except "\" or newline or the quote>
    longbyteschar  ::=  <any ASCII character except "\">
    bytesescapeseq ::=  "\" <any ASCII character>

     

    One syntactic restriction not indicated by these productions is that whitespace is not allowed between the stringprefix or bytesprefix and the rest of the literal. The source character set is defined by the encoding declaration; it is UTF-8 if no encoding declaration is given in the source file; see section Encoding declarations.

    In plain English: Both types of literals can be enclosed in matching single quotes (') or double quotes ("). They can also be enclosed in matching groups of three single or double quotes (these are generally referred to as triple-quoted strings). The backslash (\) character is used to give special meaning to otherwise ordinary characters like n, which means ‘newline’ when escaped (\n). It can also be used to escape characters that otherwise have a special meaning, such as newline, backslash itself, or the quote character. See escape sequences below for examples.

    Bytes literals are always prefixed with 'b' or 'B'; they produce an instance of the bytes type instead of the str type. They may only contain ASCII characters; bytes with a numeric value of 128 or greater must be expressed with escapes.

    Both string and bytes literals may optionally be prefixed with a letter 'r' or 'R'; such strings are called raw strings and treat backslashes as literal characters. As a result, in string literals, '\U' and '\u' escapes in raw strings are not treated specially. Given that Python 2.x’s raw unicode literals behave differently than Python 3.x’s the 'ur' syntax is not supported.

    New in version 3.3: The 'rb' prefix of raw bytes literals has been added as a synonym of 'br'.

    Support for the unicode legacy literal (u'value') was reintroduced to simplify the maintenance of dual Python 2.x and 3.x codebases. See PEP 414 for more information.

    A string literal with 'f' or 'F' in its prefix is a formatted string literal; see f-strings. The 'f' may be combined with 'r', but not with 'b' or 'u', therefore raw formatted strings are possible, but formatted bytes literals are not.

    In triple-quoted literals, unescaped newlines and quotes are allowed (and are retained), except that three unescaped quotes in a row terminate the literal. (A “quote” is the character used to open the literal, i.e. either ' or ".)

    이러한 프로덕션에서 표시되지 않는 한 가지 구문 제한은 stringprefix 또는 bytesprefix와 나머지 리터럴 사이에 공백이 허용되지 않는다는 것이다. 소스 문자 세트는 인코딩 선언에 의해 정의된다. 소스 파일에 인코딩 선언이 없으면 UTF-8이다. 인코딩 선언 섹션을 참조한다.

    일반 영어: 두 가지 유형의 리터럴 모두 일치하는 작은 따옴표(') 또는 큰 따옴표(")로 묶일 수 있다. 또한 세 개의 작은 따옴표 또는 큰 따옴표로 구성된 일치 그룹으로 묶일 수도 있다(일반적으로 삼중 따옴표 문자열이라고 함). 백슬래시(\) 문자는 n과 같은 일반 문자에 특별한 의미를 부여하는 데 사용되며, 이는 이스케이프(\n)될 때 '줄바꿈'을 의미한다. 또한 다음과 같이 특별한 의미를 갖는 문자를 이스케이프하는 데에도 사용할 수 있다. 줄 바꿈, 백슬래시 자체 또는 따옴표 문자 예를 보려면 아래 이스케이프 시퀀스를 참조한다.

    바이트 리터럴에는 항상 'b' 또는 'B' 접두사가 붙는다. str 유형 대신 bytes 유형의 인스턴스를 생성한다. ASCII 문자만 포함할 수 있다. 숫자 값이 128 이상인 바이트는 이스케이프를 사용하여 표현해야 한다.

    문자열과 바이트 리터럴 모두 선택적으로 문자 'r' 또는 'R'이 앞에 붙을 수 있다. 이러한 문자열을 원시 문자열이라고 하며 백슬래시를 리터럴 문자로 처리한다. 결과적으로 문자열 리터럴에서 원시 문자열의 '\U' 및 '\u' 이스케이프는 특별히 처리되지 않는다. Python 2.x의 원시 유니코드 리터럴이 Python 3.x의 것과 다르게 동작한다는 점을 고려하면 'ur' 구문은 지원되지 않는다.

    버전 3.3에 추가됨: 원시 바이트 리터럴의 'rb' 접두사가 'br'의 동의어로 추가되었다.

    듀얼 Python 2.x 및 3.x 코드베이스의 유지 관리를 단순화하기 위해 유니코드 레거시 리터럴(u'value')에 대한 지원이 다시 도입되었다. 자세한 내용은 PEP 414를 참조한다.

    접두사에 'f' 또는 'F'가 있는 문자열 리터럴은 형식이 지정된 문자열 리터럴이다. f-문자열을 참조한다. 'f'는 'r'과 결합할 수 있지만 'b' 또는 'u'와는 결합할 수 없다. 따라서 원시 형식 문자열은 가능하지만 형식 바이트 리터럴은 불가능하다.

    삼중 따옴표로 묶인 리터럴에서는 이스케이프되지 않은 줄바꿈과 따옴표가 허용된다(그리고 유지된다). 단, 연속된 세 개의 이스케이프되지 않은 따옴표가 리터럴을 종료한다는 점은 예외이다. ("따옴표"는 리터럴을 여는 데 사용되는 문자이다(예: ' 또는 ").)

    2.4.1.1. Escape sequences

    Unless an 'r' or 'R' prefix is present, escape sequences in string and bytes literals are interpreted according to rules similar to those used by Standard C. The recognized escape sequences are:

    'r' 또는 'R' 접두사가 없으면 문자열 및 바이트 리터럴의 이스케이프 시퀀스는 표준 C에서 사용되는 것과 유사한 규칙에 따라 해석된다. 인식되는 이스케이프 시퀀스는 다음과 같다.

     

    Escape Sequence Meaning Notes
    \\ Backslash (\)  
    \' Single quote (')  
    \" Double quote (")  
    \a ASCII Bell (BEL)  
    \b ASCII Backspace (BS)  
    \f ASCII Formfeed (FF)  
    \n ASCII Linefeed (LF)  
    \r ASCII Carriage Return (CR)  
    \t ASCII Horizontal Tab (TAB)  
    \v ASCII Vertical Tab (VT)  
    \ooo Character with octal value ooo (2,4)
    \xhh Character with hex value hh (3,4)

     

    이스케이프 시퀀스 의미 노트
    \\ 백슬래시(\)  
    \' 작은따옴표(')  
    \" 큰따옴표(")  
    \a ASCII 벨(BEL)  
    \b ASCII 백스페이스(BS)  
    \f ASCII 폼피드(FF)  
    \n ASCII 라인피드(LF)  
    \r ASCII 캐리지 리턴(CR)  
    \t ASCII 수평 탭(TAB)  
    \v ASCII 수직 탭(VT)  
    \ooo 8진수 값을 갖는 문자 ooo (2,4)
    \xhh 16진수 값이 hh인 문자 (3,4)

     

    Escape sequences only recognized in string literals are:

    문자열 리터럴에서만 인식되는 이스케이프 시퀀스는 다음과 같다.

     

    Escape Sequence Meaning Notes
    \uxxxx Character with 16-bit hex value xxxx (6)
    \Uxxxxxxxx Character with 32-bit hex value xxxxxxxx (7)

     

    이스케이프 시퀀스 의미 노트
    \uxxxx 16비트 16진수 값 xxxx를 갖는 문자 (6)
    \Uxxxxxxxx 32비트 16진수 값 xxxxxxx를 갖는 문자 (7)

     

    Notes:

    1. A backslash can be added at the end of a line to ignore the newline:

    줄바꿈을 무시하려면 줄 끝에 백슬래시를 추가할 수 있다.

    'This string will not include \
    backslashes or newline characters.'
    'This string will not include backslashes or newline characters.'

     

    The same result can be achieved using triple-quoted strings, or parentheses and string literal concatenation.

    삼중따옴표로 묶인 문자열이나 괄호 및 문자열 리터럴 연결을 사용하여 동일한 결과를 얻을 수 있다.

     

    2. As in Standard C, up to three octal digits are accepted.

    Changed in version 3.11: Octal escapes with value larger than 0o377 produce a DeprecationWarning.

    Changed in version 3.12: Octal escapes with value larger than 0o377 produce a SyntaxWarning. In a future Python version they will be eventually a SyntaxError.

    표준 C와 마찬가지로 최대 3개의 8진수 숫자가 허용된다.

    버전 3.11에서 변경: 0o377보다 큰 값을 갖는 8진수 이스케이프는 DeprecationWarning을 생성한다.

    버전 3.12에서 변경: 0o377보다 큰 값을 갖는 8진수 이스케이프는 SyntaxWarning을 생성한다. 향후 Python 버전에서는 결국 SyntaxError가 될 것이다.

     

    3. Unlike in Standard C, exactly two hex digits are required.

    표준 C와 달리 정확히 두 개의 16진수가 필요하다.

     

    4. In a bytes literal, hexadecimal and octal escapes denote the byte with the given value. In a string literal, these escapes denote a Unicode character with the given value.

    바이트 리터럴에서 16진수 및 8진수 이스케이프는 주어진 값을 가진 바이트를 나타낸다. 문자열 리터럴에서 이러한 이스케이프는 지정된 값을 가진 유니코드 문자를 나타낸다.

     

    5. Changed in version 3.3: Support for name aliases [1] has been added.

    버전 3.3에서 변경: 이름 별칭 [1]에 대한 지원이 추가되었다.

     

    6. Exactly four hex digits are required.

    정확히 4개의 16진수가 필요하다.

     

    7. Any Unicode character can be encoded this way. Exactly eight hex digits are required.

    모든 유니코드 문자는 이 방법으로 인코딩될 수 있다. 정확히 8개의 16진수가 필요하다.

     

    Unlike Standard C, all unrecognized escape sequences are left in the string unchanged, i.e., the backslash is left in the result. (This behavior is useful when debugging: if an escape sequence is mistyped, the resulting output is more easily recognized as broken.) It is also important to note that the escape sequences only recognized in string literals fall into the category of unrecognized escapes for bytes literals.

    Changed in version 3.6: Unrecognized escape sequences produce a DeprecationWarning.

    Changed in version 3.12: Unrecognized escape sequences produce a SyntaxWarning. In a future Python version they will be eventually a SyntaxError.

    Even in a raw literal, quotes can be escaped with a backslash, but the backslash remains in the result; for example, r"\"" is a valid string literal consisting of two characters: a backslash and a double quote; r"\" is not a valid string literal (even a raw string cannot end in an odd number of backslashes). Specifically, a raw literal cannot end in a single backslash (since the backslash would escape the following quote character). Note also that a single backslash followed by a newline is interpreted as those two characters as part of the literal, not as a line continuation.

    표준 C와 달리 인식되지 않은 모든 이스케이프 시퀀스는 문자열에 변경되지 않은 채 남아 있다. 즉, 백슬래시가 결과에 남는다. (이 동작은 디버깅할 때 유용하다. 이스케이프 시퀀스를 잘못 입력하면 결과 출력이 깨진 것으로 더 쉽게 인식된다.) 문자열 리터럴에서만 인식되는 이스케이프 시퀀스는 바이트 리터럴에 대해 인식되지 않는 이스케이프 범주에 속한다는 점에 유의하는 것도 중요하다.

    버전 3.6에서 변경: 인식할 수 없는 이스케이프 시퀀스는 DeprecationWarning을 생성한다.

    버전 3.12에서 변경: 인식할 수 없는 이스케이프 시퀀스는 SyntaxWarning을 생성한다. 향후 Python 버전에서는 결국 SyntaxError가 될 것이다.

    원시 리터럴에서도 백슬래시를 사용하여 따옴표를 이스케이프할 수 있지만 결과에는 백슬래시가 남아 있다. 예를 들어, r"\""는 백슬래시와 큰따옴표라는 두 문자로 구성된 유효한 문자열 리터럴이다. r"\"는 유효한 문자열 리터럴이 아니다(원시 문자열이라도 홀수 개의 백슬래시로 끝날 수 없음). 특히, 원시 리터럴은 단일 백슬래시로 끝날 수 없다(백슬래시는 다음 인용 문자를 이스케이프하기 때문이다.) 또한 단일 백슬래시 뒤에 개행 문자가 오면 줄 연속이 아니라 리터럴의 일부인 두 문자로 해석된다.

    2.4.2. String literal concatenation

    Multiple adjacent string or bytes literals (delimited by whitespace), possibly using different quoting conventions, are allowed, and their meaning is the same as their concatenation. Thus, "hello" 'world' is equivalent to "helloworld". This feature can be used to reduce the number of backslashes needed, to split long strings conveniently across long lines, or even to add comments to parts of strings, for example:

    서로 다른 인용 규칙을 사용할 수 있는 여러 인접 문자열 또는 바이트 리터럴(공백으로 구분)이 허용되며 그 의미는 연결과 동일하다. 따라서 "hello" 'world'는 "helloworld"와 동일하다. 이 기능을 사용하면 필요한 백슬래시 수를 줄이고 긴 문자열을 긴 줄에 걸쳐 편리하게 분할하거나 문자열 일부에 주석을 추가할 수도 있다. 예를 들면 다음과 같다.

    re.compile("[A-Za-z_]"       # letter or underscore
               "[A-Za-z0-9_]*"   # letter, digit or underscore
              )

     

    Note that this feature is defined at the syntactical level, but implemented at compile time. The ‘+’ operator must be used to concatenate string expressions at run time. Also note that literal concatenation can use different quoting styles for each component (even mixing raw strings and triple quoted strings), and formatted string literals may be concatenated with plain string literals.

    이 기능은 구문 수준에서 정의되지만 컴파일 타임에 구현된다. 런타임에 문자열 표현식을 연결하려면 '+' 연산자를 사용해야 한다. 또한 리터럴 연결은 각 구성 요소에 대해 서로 다른 인용 스타일을 사용할 수 있으며(원시 문자열과 삼중 인용 문자열을 혼합하는 경우에도) 형식이 지정된 문자열 리터럴은 일반 문자열 리터럴과 연결될 수 있다.

    2.4.3. f-strings

    New in version 3.6.

    A formatted string literal or f-string is a string literal that is prefixed with 'f' or 'F'. These strings may contain replacement fields, which are expressions delimited by curly braces {}. While other string literals always have a constant value, formatted strings are really expressions evaluated at run time.

    Escape sequences are decoded like in ordinary string literals (except when a literal is also marked as a raw string). After decoding, the grammar for the contents of the string is:

    버전 3.6의 새로운 기능이다.

    형식화된 문자열 리터럴 또는 f-string은 'f' 또는 'F' 접두사가 붙는 문자열 리터럴이다. 이러한 문자열에는 중괄호 {}로 구분된 표현식인 대체 필드가 포함될 수 있다. 다른 문자열 리터럴은 항상 상수 값을 가지지만 형식이 지정된 문자열은 실제로 런타임에 평가되는 표현식이다.

    이스케이프 시퀀스는 일반 문자열 리터럴처럼 디코딩된다(리터럴이 원시 문자열로도 표시되는 경우 제외). 디코딩 후 문자열 내용의 문법은 다음과 같다.

    f_string          ::=  (literal_char | "{{" | "}}" | replacement_field)*
    replacement_field ::=  "{" f_expression ["="] ["!" conversion] [":" format_spec] "}"
    f_expression      ::=  (conditional_expression | "*" or_expr)
                             ("," conditional_expression | "," "*" or_expr)* [","]
                           | yield_expression
    conversion        ::=  "s" | "r" | "a"
    format_spec       ::=  (literal_char | NULL | replacement_field)*
    literal_char      ::=  <any code point except "{", "}" or NULL>

     

    The parts of the string outside curly braces are treated literally, except that any doubled curly braces '{{' or '}}' are replaced with the corresponding single curly brace. A single opening curly bracket '{' marks a replacement field, which starts with a Python expression. To display both the expression text and its value after evaluation, (useful in debugging), an equal sign '=' may be added after the expression. A conversion field, introduced by an exclamation point '!' may follow. A format specifier may also be appended, introduced by a colon ':'. A replacement field ends with a closing curly bracket '}'.

    Expressions in formatted string literals are treated like regular Python expressions surrounded by parentheses, with a few exceptions. An empty expression is not allowed, and both lambda and assignment expressions := must be surrounded by explicit parentheses. Each expression is evaluated in the context where the formatted string literal appears, in order from left to right. Replacement expressions can contain newlines in both single-quoted and triple-quoted f-strings and they can contain comments. Everything that comes after a # inside a replacement field is a comment (even closing braces and quotes). In that case, replacement fields must be closed in a different line.

    중괄호 밖의 문자열 부분은 문자 그대로 처리된다. 단, 이중 중괄호 '{{' 또는 '}}'는 해당하는 단일 중괄호로 대체된다. 단일 여는 중괄호 '{'는 Python 표현식으로 시작하는 대체 필드를 표시한다. 평가 후 표현식 텍스트와 해당 값을 모두 표시하려면(디버깅에 유용함) 표현식 뒤에 등호 '='를 추가할 수 있다. 느낌표 '!'로 시작되는 변환 필드 따를 수 있다. 형식 지정자는 콜론 ':'으로 시작하여 추가될 수도 있다. 대체 필드는 닫는 중괄호 '}'로 끝난다.

    형식이 지정된 문자열 리터럴의 표현식은 몇 가지 예외를 제외하고 괄호로 묶인 일반 Python 표현식처럼 처리된다. 빈 표현식은 허용되지 않으며 람다 및 대입 표현식 :=은 모두 명시적인 괄호로 묶어야 한다. 각 표현식은 형식화된 문자열 리터럴이 나타나는 컨텍스트에서 왼쪽에서 오른쪽으로 평가된다. 대체 표현식은 작은 따옴표와 삼중 따옴표로 묶인 f-문자열 모두에 줄 바꿈을 포함할 수 있으며 주석을 포함할 수 있다. 대체 필드 내에서 # 뒤에 오는 모든 내용은 주석이다(닫는 중괄호와 따옴표 포함). 이 경우 대체 필드는 다른 줄에서 닫혀야 한다.

    f"abc{a # This is a comment }"
    ... + 3}"
    'abc5'

     

    Changed in version 3.7: Prior to Python 3.7, an await expression and comprehensions containing an async for clause were illegal in the expressions in formatted string literals due to a problem with the implementation.

    Changed in version 3.12: Prior to Python 3.12, comments were not allowed inside f-string replacement fields.

    When the equal sign '=' is provided, the output will have the expression text, the '=' and the evaluated value. Spaces after the opening brace '{', within the expression and after the '=' are all retained in the output. By default, the '=' causes the repr() of the expression to be provided, unless there is a format specified. When a format is specified it defaults to the str() of the expression unless a conversion '!r' is declared.

    New in version 3.8: The equal sign '='.

    If a conversion is specified, the result of evaluating the expression is converted before formatting. Conversion '!s' calls str() on the result, '!r' calls repr(), and '!a' calls ascii().

    The result is then formatted using the format() protocol. The format specifier is passed to the __format__() method of the expression or conversion result. An empty string is passed when the format specifier is omitted. The formatted result is then included in the final value of the whole string.

    Top-level format specifiers may include nested replacement fields. These nested fields may include their own conversion fields and format specifiers, but may not include more deeply nested replacement fields. The format specifier mini-language is the same as that used by the str.format() method.

    Formatted string literals may be concatenated, but replacement fields cannot be split across literals.

    Some examples of formatted string literals:

    버전 3.7에서 변경: Python 3.7 이전에는 구현 문제로 인해 형식이 지정된 문자열 리터럴의 표현식에서 async for 절을 포함하는 wait 표현식과 comprehension이 잘못된 표현이었다.

    버전 3.12에서 변경: Python 3.12 이전에는 f-문자열 대체 필드 내에 주석이 허용되지 않았다.

    등호 '='가 제공되면 출력에는 표현식 텍스트, '=' 및 평가된 값이 포함된다. 여는 중괄호 '{' 뒤, 표현식 내 및 '=' 뒤의 공백은 모두 출력에 유지된다. 기본적으로 '='는 지정된 형식이 없는 한 표현식의 repr()이 제공되도록 한다. 형식이 지정되면 변환 '!r'이 선언되지 않는 한 기본적으로 표현식의 str()이 사용된다.

    버전 3.8의 새로운 기능: 등호 '='.

    변환이 지정된 경우 형식 지정 전에 표현식 평가 결과가 변환된다. 변환 '!s'는 결과에 대해 str()을 호출하고, '!r'은 repr()을 호출하고, '!a'는 ascii()를 호출한다.

    그런 다음 결과는 format() 프로토콜을 사용하여 형식화된다. 형식 지정자는 표현식 또는 변환 결과의 __format__() 메서드에 전달된다. 형식 지정자가 생략되면 빈 문자열이 전달된다. 그러면 형식화된 결과가 전체 문자열의 최종 값에 포함된다.

    최상위 형식 지정자에는 중첩된 대체 필드가 포함될 수 있다. 이러한 중첩 필드에는 자체 변환 필드와 형식 지정자가 포함될 수 있지만 더 깊이 중첩된 대체 필드는 포함되지 않을 수 있다. 형식 지정자 미니 언어는 str.format() 메서드에서 사용되는 것과 동일하다.

    형식화된 문자열 리터럴은 연결될 수 있지만 대체 필드는 리터럴 간에 분할될 수 없다.

    형식화된 문자열 리터럴의 몇 가지 예:

    name = "Fred"
    f"He said his name is {name!r}."
    "He said his name is 'Fred'."
    f"He said his name is {repr(name)}."  # repr() is equivalent to !r
    "He said his name is 'Fred'."
    width = 10
    precision = 4
    value = decimal.Decimal("12.34567")
    f"result: {value:{width}.{precision}}"  # nested fields
    'result:      12.35'
    today = datetime(year=2017, month=1, day=27)
    f"{today:%B %d, %Y}"  # using date format specifier
    'January 27, 2017'
    f"{today=:%B %d, %Y}" # using date format specifier and debugging
    'today=January 27, 2017'
    number = 1024
    f"{number:#0x}"  # using integer format specifier
    '0x400'
    foo = "bar"
    f"{ foo = }" # preserves whitespace
    " foo = 'bar'"
    line = "The mill's closed"
    f"{line = }"
    'line = "The mill\'s closed"'
    f"{line = :20}"
    "line = The mill's closed   "
    f"{line = !r:20}"
    'line = "The mill\'s closed" '

     

    Reusing the outer f-string quoting type inside a replacement field is permitted:

    대체 필드 내에서 외부 f-문자열 인용 유형을 재사용하는 것이 허용된다.

    a = dict(x=2)
    f"abc {a["x"]} def"
    'abc 2 def'

     

    Changed in version 3.12: Prior to Python 3.12, reuse of the same quoting type of the outer f-string inside a replacement field was not possible.

    Backslashes are also allowed in replacement fields and are evaluated the same way as in any other context:

    버전 3.12에서 변경: Python 3.12 이전에는 대체 필드 내에서 외부 f-문자열의 동일한 인용 유형을 재사용하는 것이 불가능했다.

    백슬래시는 대체 필드에서도 허용되며 다른 컨텍스트에서와 동일한 방식으로 평가된다.

    a = ["a", "b", "c"]
    print(f"List a contains:\n{"\n".join(a)}")
    List a contains:
    a
    b
    c

     

    Changed in version 3.12: Prior to Python 3.12, backslashes were not permitted inside an f-string replacement field.

    Formatted string literals cannot be used as docstrings, even if they do not include expressions.

    버전 3.12에서 변경: Python 3.12 이전에는 f-문자열 대체 필드 내에서 백슬래시가 허용되지 않았다.

    형식화된 문자열 리터럴은 표현식을 포함하지 않더라도 독스트링으로 사용할 수 없다.

    def foo():
        f"Not a docstring"
    
    foo.__doc__ is None
    True

     

    See also PEP 498 for the proposal that added formatted string literals, and str.format(), which uses a related format string mechanism.

    형식화된 문자열 리터럴과 관련 형식 문자열 메커니즘을 사용하는 str.format()을 추가하는 제안은 PEP 498을 참조한다.

    2.4.4. Numeric literals

     

    There are three types of numeric literals: integers, floating point numbers, and imaginary numbers. There are no complex literals (complex numbers can be formed by adding a real number and an imaginary number).

    Note that numeric literals do not include a sign; a phrase like -1 is actually an expression composed of the unary operator ‘-’ and the literal 1.

    숫자 리터럴에는 정수, 부동 소수점 숫자, 허수라는 세 가지 유형이 있다. 복소수 리터럴은 없다(복소수는 실수와 허수를 더하여 형성될 수 있음).

    숫자 리터럴에는 기호가 포함되지 않는다. -1과 같은 구문은 실제로 단항 연산자 '-'와 리터럴 1로 구성된 표현식이다.

    2.4.5. Integer literals

    Integer literals are described by the following lexical definitions:

    정수 리터럴은 다음 어휘 정의로 설명된다.

    integer      ::=  decinteger | bininteger | octinteger | hexinteger
    decinteger   ::=  nonzerodigit (["_"] digit)* | "0"+ (["_"] "0")*
    bininteger   ::=  "0" ("b" | "B") (["_"] bindigit)+
    octinteger   ::=  "0" ("o" | "O") (["_"] octdigit)+
    hexinteger   ::=  "0" ("x" | "X") (["_"] hexdigit)+
    nonzerodigit ::=  "1"..."9"
    digit        ::=  "0"..."9"
    bindigit     ::=  "0" | "1"
    octdigit     ::=  "0"..."7"
    hexdigit     ::=  digit | "a"..."f" | "A"..."F"

     

    There is no limit for the length of integer literals apart from what can be stored in available memory.

    Underscores are ignored for determining the numeric value of the literal. They can be used to group digits for enhanced readability. One underscore can occur between digits, and after base specifiers like 0x.

    Note that leading zeros in a non-zero decimal number are not allowed. This is for disambiguation with C-style octal literals, which Python used before version 3.0.

    Some examples of integer literals:

    사용 가능한 메모리에 저장할 수 있는 것 외에 정수 리터럴의 길이에는 제한이 없다.

    리터럴의 숫자 값을 결정할 때 밑줄은 무시된다. 가독성을 높이기 위해 숫자를 그룹화하는 데 사용할 수 있다. 밑줄은 숫자 사이와 0x와 같은 기본 지정자 뒤에 나타날 수 있다.

    0이 아닌 십진수에는 앞에 0을 붙이는 것이 허용되지 않는다. 이는 Python이 버전 3.0 이전에 사용했던 C 스타일 8진수 리터럴을 명확하게 하기 위한 것이다.

    정수 리터럴의 몇 가지 예:

    7     2147483647                        0o177    0b100110111
    3     79228162514264337593543950336     0o377    0xdeadbeef
          100_000_000_000                   0b_1110_0101

     

    Changed in version 3.6: Underscores are now allowed for grouping purposes in literals.

    버전 3.6에서 변경: 이제 리터럴의 그룹화 목적으로 밑줄이 허용된다.

    2.4.6. Floating point literals

    Floating point literals are described by the following lexical definitions:

    부동 소수점 리터럴은 다음 어휘 정의로 설명된다.

    floatnumber   ::=  pointfloat | exponentfloat
    pointfloat    ::=  [digitpart] fraction | digitpart "."
    exponentfloat ::=  (digitpart | pointfloat) exponent
    digitpart     ::=  digit (["_"] digit)*
    fraction      ::=  "." digitpart
    exponent      ::=  ("e" | "E") ["+" | "-"] digitpart

     

    Note that the integer and exponent parts are always interpreted using radix 10. For example, 077e010 is legal, and denotes the same number as 77e10. The allowed range of floating point literals is implementation-dependent. As in integer literals, underscores are supported for digit grouping.

    Some examples of floating point literals:

    정수 및 지수 부분은 항상 기수 10을 사용하여 해석된다. 예를 들어 077e010은 유효하며 77e10과 동일한 숫자를 나타낸다. 부동 소수점 리터럴의 허용 범위는 구현에 따라 다릅니다. 정수 리터럴과 마찬가지로 숫자 그룹화에는 밑줄이 지원된다.

    부동 소수점 리터럴의 몇 가지 예:

    3.14    10.    .001    1e100    3.14e-10    0e0    3.14_15_93

     

    Changed in version 3.6: Underscores are now allowed for grouping purposes in literals.

    버전 3.6에서 변경: 이제 리터럴의 그룹화 목적으로 밑줄이 허용된다.

    2.4.7. Imaginary literals

     

    Imaginary literals are described by the following lexical definitions:

    허수 리터럴은 다음 어휘 정의로 설명된다.

    imagnumber ::=  (floatnumber | digitpart) ("j" | "J")

     

    An imaginary literal yields a complex number with a real part of 0.0. Complex numbers are represented as a pair of floating point numbers and have the same restrictions on their range. To create a complex number with a nonzero real part, add a floating point number to it, e.g., (3+4j). Some examples of imaginary literals:

    허수 리터럴은 실수 부분이 0.0인 복소수를 생성한다. 복소수는 부동 소수점 숫자 쌍으로 표시되며 범위에 대해 동일한 제한 사항이 있다. 0이 아닌 실수 부분으로 복소수를 생성하려면 여기에 부동 소수점 수를 추가한다(예: (3+4j)). 허수 리터럴의 몇 가지 예:

    3.14j   10.j    10j     .001j   1e100j   3.14e-10j   3.14_15_93j

    2.5. Operators

    The following tokens are operators:

    다음 토큰은 연산자이다.

    +       -       *       **      /       //      %      @
    <<      >>      &       |       ^       ~       :=
    <       >       <=      >=      ==      !=

    2.6. Delimiters

    The following tokens serve as delimiters in the grammar:

    다음 토큰은 문법에서 구분 기호 역할을 한다.

    (       )       [       ]       {       }
    ,       :       .       ;       @       =       ->
    +=      -=      *=      /=      //=     %=      @=
    &=      |=      ^=      >>=     <<=     **=

     

    The period can also occur in floating-point and imaginary literals. A sequence of three periods has a special meaning as an ellipsis literal. The second half of the list, the augmented assignment operators, serve lexically as delimiters, but also perform an operation.

    The following printing ASCII characters have special meaning as part of other tokens or are otherwise significant to the lexical analyzer:

    마침표는 부동 소수점 및 허수 리터럴에서도 나타날 수 있다. 세 개의 마침표로 구성된 시퀀스는 줄임표 리터럴로서 특별한 의미를 갖는다. 목록의 후반부인 추가 할당 연산자는 어휘적으로 구분 기호 역할을 할 뿐만 아니라 작업도 수행한다.

    다음 인쇄 ASCII 문자는 다른 토큰의 일부로서 특별한 의미를 갖거나 어휘 분석기에 중요하다.

    '       "       #       \

     

    The following printing ASCII characters are not used in Python. Their occurrence outside string literals and comments is an unconditional error:

    다음 인쇄 ASCII 문자는 Python에서 사용되지 않는다. 문자열 리터럴과 주석 외부에서 발생하는 것은 무조건적인 오류이다.

    $       ?       `

    Footnotes

    [1]

    https://www.unicode.org/Public/15.0.0/ucd/NameAliases.txt 

     

    Python/Reference/소개

     

    Python/Reference/소개

    파이썬을 사용하면서 파이썬 매뉴얼을 참고해야 할 경우가 있다. 이럴 경우 매뉴얼의 구성과 용어에 대해 알고 접근하는 것이 도움이 된다. 그래서 매뉴얼을 설명하는 챕터 1과 2를 번역해 올린

    summertrees.tistory.com

     

    728x90

    댓글

Designed by Tistory.