2.Lexical analysis¶
A Python program is read by aparser. Input to the parser is a stream oftokens, generated by thelexical analyzer (also known asthetokenizer).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 filecan be given by an encoding declaration and defaults to UTF-8, seePEP 3120for details. If the source file cannot be decoded, aSyntaxError
israised.
2.1.Line structure¶
A Python program is divided into a number oflogical lines.
2.1.1.Logical lines¶
The end of a logical line is represented by the tokenNEWLINE
.Statements cannot cross logical line boundaries except whereNEWLINE
is allowed by the syntax (e.g., between statements in compound statements).A logical line is constructed from one or morephysical lines by followingtheexplicit orimplicitline joining rules.
2.1.2.Physical lines¶
A physical line is a sequence of characters terminated by one the followingend-of-line sequences:
the Unix form using ASCII LF (linefeed),
the Windows form using the ASCII sequence CR LF (return followed by linefeed),
the ‘Classic Mac OS’ form using the ASCII CR (return) character.
Regardless of platform, each of these sequences is replaced by a singleASCII LF (linefeed) character.(This is done even insidestring literals.)Each line can use any of the sequences; they do not need to be consistentwithin a file.
The end of input also serves as an implicit terminator for the finalphysical line.
Formally:
newline: <ASCII LF> | <ASCII CR> <ASCII LF> | <ASCII CR>
2.1.3.Comments¶
A comment starts with a hash character (#
) that is not part of a stringliteral, and ends at the end of the physical line. A comment signifies the endof the logical line unless the implicit line joining rules are invoked. Commentsare ignored by the syntax.
2.1.4.Encoding declarations¶
If a comment in the first or second line of the Python script matches theregular expressioncoding[=:]\s*([-\w.]+)
, this comment is processed as anencoding declaration; the first group of this expression names the encoding ofthe source code file. The encoding declaration must appear on a line of itsown. If it is the second line, the first line must also be a comment-only line.The recommended forms of an encoding expression are
# -*- coding: <encoding-name> -*-
which is recognized also by GNU Emacs, and
# vim:fileencoding=<encoding-name>
which is recognized by Bram Moolenaar’s VIM.
If no encoding declaration is found, the default encoding is UTF-8. If theimplicit or explicit encoding of a file is UTF-8, an initial UTF-8 byte-ordermark (b'\xef\xbb\xbf'
) is ignored rather than being a syntax error.
If an encoding is declared, the encoding name must be recognized by Python(seeStandard Encodings). Theencoding is used for all lexical analysis, including string literals, commentsand identifiers.
All lexical analysis, including string literals, commentsand identifiers, works on Unicode text decoded using the source encoding.Any Unicode code point, except the NUL control character, can appear inPython source.
source_character: <any Unicode code point, except NUL>
2.1.5.Explicit line joining¶
Two or more physical lines may be joined into logical lines using backslashcharacters (\
), as follows: when a physical line ends in a backslash that isnot part of a string literal or comment, it is joined with the following forminga single logical line, deleting the backslash and the following end-of-linecharacter. For example:
if1900<year<2100and1<=month<=12 \and1<=day<=31and0<=hour<24 \and0<=minute<60and0<=second<60:# Looks like a valid datereturn1
A line ending in a backslash cannot carry a comment. A backslash does notcontinue a comment. A backslash does not continue a token except for stringliterals (i.e., tokens other than string literals cannot be split acrossphysical lines using a backslash). A backslash is illegal elsewhere on a lineoutside a string literal.
2.1.6.Implicit line joining¶
Expressions in parentheses, square brackets or curly braces can be split overmore 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 thecontinuation lines is not important. Blank continuation lines are allowed.There is no NEWLINE token between implicit continuation lines. Implicitlycontinued lines can also occur within triple-quoted strings (see below); in thatcase they cannot carry comments.
2.1.7.Blank lines¶
A logical line that contains only spaces, tabs, formfeeds and possibly acomment, is ignored (i.e., noNEWLINE
token is generated).During interactive input of statements, handling of a blank line may differdepending on the implementation of the read-eval-print loop.In the standard interactive interpreter, an entirely blank logical line (thatis, one containing not even whitespace or a comment) terminates a multi-linestatement.
2.1.8.Indentation¶
Leading whitespace (spaces and tabs) at the beginning of a logical line is usedto compute the indentation level of the line, which in turn is used to determinethe grouping of statements.
Tabs are replaced (from left to right) by one to eight spaces such that thetotal number of characters up to and including the replacement is a multiple ofeight (this is intended to be the same rule as used by Unix). The total numberof spaces preceding the first non-blank character then determines the line’sindentation. Indentation cannot be split over multiple physical lines usingbackslashes; the whitespace up to the first backslash determines theindentation.
Indentation is rejected as inconsistent if a source file mixes tabs and spacesin a way that makes the meaning dependent on the worth of a tab in spaces; aTabError
is raised in that case.
Cross-platform compatibility note: because of the nature of text editors onnon-UNIX platforms, it is unwise to use a mixture of spaces and tabs for theindentation in a single source file. It should also be noted that differentplatforms may explicitly limit the maximum indentation level.
A formfeed character may be present at the start of the line; it will be ignoredfor the indentation calculations above. Formfeed characters occurring elsewherein the leading whitespace have an undefined effect (for instance, they may resetthe space count to zero).
The indentation levels of consecutive lines are used to generateINDENT
andDEDENT
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 willalways be strictly increasing from bottom to top. At the beginning of eachlogical 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, andoneINDENT
token is generated. If it is smaller, itmust be one of thenumbers occurring on the stack; all numbers on the stack that are larger arepopped off, and for each number popped off aDEDENT
token is generated.At the end of the file, aDEDENT
token is generated for each numberremaining on the stack that is larger than zero.
Here is an example of a correctly (though confusingly) indented piece of Pythoncode:
defperm(l):# Compute the list of all permutations of liflen(l)<=1:return[l]r=[]foriinrange(len(l)):s=l[:i]+l[i+1:]p=perm(s)forxinp:r.append(l[i:i+1]+x)returnr
The following example shows various indentation errors:
defperm(l):# error: first line indentedforiinrange(len(l)):# error: not indenteds=l[:i]+l[i+1:]p=perm(l[:i]+l[i+1:])# error: unexpected indentforxinp:r.append(l[i:i+1]+x)returnr# error: inconsistent dedent
(Actually, the first three errors are detected by the parser; only the lasterror is found by the lexical analyzer — the indentation ofreturnr
doesnot match a level popped off the stack.)
2.1.9.Whitespace between tokens¶
Except at the beginning of a logical line or in string literals, the whitespacecharacters space, tab and formfeed can be used interchangeably to separatetokens. Whitespace is needed between two tokens only if their concatenationcould otherwise be interpreted as a different token. For example,ab
is onetoken, butab
is two tokens. However,+a
and+a
both producetwo tokens,+
anda
, as+a
is not a valid token.
2.1.10.End marker¶
At the end of non-interactive input, the lexical analyzer generates anENDMARKER
token.
2.2.Other tokens¶
BesidesNEWLINE
,INDENT
andDEDENT
,the following categories of tokens exist:identifiers andkeywords (NAME
),literals (such asNUMBER
andSTRING
), and other symbols(operators anddelimiters,OP
).Whitespace characters (other than logical line terminators, discussed earlier)are not tokens, but serve to delimit tokens.Where ambiguity exists, a token comprises the longest possible string thatforms a legal token, when read from left to right.
2.3.Names (identifiers and keywords)¶
NAME
tokens representidentifiers,keywords, andsoft keywords.
Within the ASCII range (U+0001..U+007F), the valid characters for namesinclude the uppercase and lowercase letters (A-Z
anda-z
),the underscore_
and, except for the first character, the digits0
through9
.
Names must contain at least one character, but have no upper length limit.Case is significant.
BesidesA-Z
,a-z
,_
and0-9
, names can also use “letter-like”and “number-like” characters from outside the ASCII range, as detailed below.
All identifiers are converted into thenormalization form NFKC whileparsing; comparison of identifiers is based on NFKC.
Formally, the first character of a normalized identifier must belong to thesetid_start
, which is the union of:
Unicode category
<Lu>
- uppercase letters (includesA
toZ
)Unicode category
<Ll>
- lowercase letters (includesa
toz
)Unicode category
<Lt>
- titlecase lettersUnicode category
<Lm>
- modifier lettersUnicode category
<Lo>
- other lettersUnicode category
<Nl>
- letter numbers{
"_"
} - the underscore<Other_ID_Start>
- an explicit set of characters inPropList.txtto support backwards compatibility
The remaining characters must belong to the setid_continue
, which is theunion of:
all characters in
id_start
Unicode category
<Nd>
- decimal numbers (includes0
to9
)Unicode category
<Pc>
- connector punctuationsUnicode category
<Mn>
- nonspacing marksUnicode category
<Mc>
- spacing combining marks<Other_ID_Continue>
- another explicit set of characters inPropList.txt to support backwards compatibility
Unicode categories use the version of the Unicode Character Database asincluded in theunicodedata
module.
These sets are based on the Unicode standard annexUAX-31.See alsoPEP 3131 for further details.
Even more formally, names are described by the following lexical definitions:
NAME:xid_start
xid_continue
*id_start: <Lu> | <Ll> | <Lt> | <Lm> | <Lo> | <Nl> |"_" | <Other_ID_Start>id_continue:id_start
| <Nd> | <Pc> | <Mn> | <Mc> | <Other_ID_Continue>xid_start: <all characters inid_start
whose NFKC normalization is in (id_start
xid_continue
*)">xid_continue: <all characters inid_continue
whose NFKC normalization is in (id_continue
*)">identifier: <NAME
, except keywords>
A non-normative listing of all valid identifier characters as defined byUnicode is available in theDerivedCoreProperties.txt file in the UnicodeCharacter Database.
2.3.1.Keywords¶
The following names are used as reserved words, orkeywords of thelanguage, and cannot be used as ordinary identifiers. They must be spelledexactly as written here:
False await else import passNone break except in raiseTrue class finally is returnand continue for lambda tryas def from nonlocal whileassert del global not withasync elif if or yield
2.3.2.Soft Keywords¶
Added in version 3.10.
Some names are only reserved under specific contexts. These are known assoft keywords:
These syntactically act as keywords in their specific contexts,but this distinction is done at the parser level, not when tokenizing.
As soft keywords, their use in the grammar is possible while stillpreserving compatibility with existing code that uses these names asidentifier names.
Changed in version 3.12:type
is now a soft keyword.
2.3.3.Reserved classes of identifiers¶
Certain classes of identifiers (besides keywords) have special meanings. Theseclasses are identified by the patterns of leading and trailing underscorecharacters:
_*
Not imported by
frommoduleimport*
._
In a
case
pattern within amatch
statement,_
is asoft keyword that denotes awildcard.Separately, the interactive interpreter makes the result of the last evaluationavailable in the variable
_
.(It is stored in thebuiltins
module, alongside built-infunctions likeprint
.)Elsewhere,
_
is a regular identifier. It is often used to name“special” items, but it is not special to Python itself.Note
The name
_
is often used in conjunction with internationalization;refer to the documentation for thegettext
module for moreinformation on this convention.It is also commonly used for unused variables.
__*__
System-defined names, informally known as “dunder” names. These names aredefined by the interpreter and its implementation (including the standard library).Current system names are discussed in theSpecial 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 tobreakage without warning.__*
Class-private names. Names in this category, when used within the context of aclass definition, are re-written to use a mangled form to help avoid nameclashes between “private” attributes of base and derived classes. See sectionIdentifiers (Names).
2.4.Literals¶
Literals are notations for constant values of some built-in types.
In terms of lexical analysis, Python hasstring, bytesandnumeric literals.
Other “literals” are lexically denoted usingkeywords(None
,True
,False
) and the specialellipsis token (...
).
2.5.String and Bytes literals¶
String literals are text enclosed in single quotes ('
) or doublequotes ("
). For example:
"spam"'eggs'
The quote used to start the literal also terminates it, so a string literalcan only contain the other quote (except with escape sequences, see below).For example:
'Say "Hello", please.'"Don't do that!"
Except for this limitation, the choice of quote character ('
or"
)does not affect how the literal is parsed.
Inside a string literal, the backslash (\
) character introduces anescape sequence, which has special meaning depending on the characterafter the backslash.For example,\"
denotes the double quote character, and doesnot endthe string:
>>>print("Say\"Hello\" to everyone!")Say "Hello" to everyone!
Seeescape sequences below for a full list of suchsequences, and more details.
2.5.1.Triple-quoted strings¶
Strings can also be enclosed in matching groups of three single or doublequotes.These are generally referred to astriple-quoted strings:
"""This is a triple-quoted string."""
In triple-quoted literals, unescaped quotes are allowed (and areretained), except that three unescaped quotes in a row terminate the literal,if they are of the same kind ('
or"
) used at the start:
"""This string has "quotes" inside."""
Unescaped newlines are also allowed and retained:
'''This triple-quoted stringcontinues on the next line.'''
2.5.2.String prefixes¶
String literals can have an optionalprefix that influences how thecontent of the literal is parsed, for example:
b"data"f'{result=}'
The allowed prefixes are:
f
:Formatted string literal (“f-string”)t
:Template string literal (“t-string”)u
: No effect (allowed for backwards compatibility)
See the linked sections for details on each type.
Prefixes are case-insensitive (for example, ‘B
’ works the same as ‘b
’).The ‘r
’ prefix can be combined with ‘f
’, ‘t
’ or ‘b
’, so ‘fr
’,‘rf
’, ‘tr
’, ‘rt
’, ‘br
’, and ‘rb
’ are also valid prefixes.
Added in version 3.3:The'rb'
prefix of raw bytes literals has been added as a synonymof'br'
.
Support for the unicode legacy literal (u'value'
) was reintroducedto simplify the maintenance of dual Python 2.x and 3.x codebases.SeePEP 414 for more information.
2.5.3.Formal grammar¶
String literals, except“f-strings” and“t-strings”, are described by thefollowing lexical definitions.
These definitions usenegative lookaheads (!
)to indicate that an ending quote ends the literal.
STRING: [stringprefix
] (stringcontent
)stringprefix: <("r" |"u" |"b" |"br" |"rb"), case-insensitive>stringcontent: |"'''" ( !"'''"longstringitem
)*"'''" |'"""' ( !'"""'longstringitem
)*'"""' |"'" ( !"'"stringitem
)*"'" |'"' ( !'"'stringitem
)*'"'stringitem:stringchar
|stringescapeseq
stringchar: <anysource_character
, except backslash and newline>longstringitem:stringitem
| newlinestringescapeseq:"\" <anysource_character
>
Note that as in all lexical definitions, whitespace is significant.In particular, the prefix (if any) must be immediately followed by the startingquote.
2.5.4.Escape sequences¶
Unless an ‘r
’ or ‘R
’ prefix is present, escape sequences in string andbytes literals are interpreted according to rules similar to those used byStandard C. The recognized escape sequences are:
Escape Sequence | Meaning |
---|---|
| |
| |
| |
| |
| ASCII Bell (BEL) |
| ASCII Backspace (BS) |
| ASCII Formfeed (FF) |
| ASCII Linefeed (LF) |
| ASCII Carriage Return (CR) |
| ASCII Horizontal Tab (TAB) |
| ASCII Vertical Tab (VT) |
| |
| |
| |
| |
|
2.5.4.1.Ignored end of line¶
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 usingtriple-quoted strings,or parentheses andstring literal concatenation.
2.5.4.2.Escaped characters¶
To include a backslash in a non-raw Python stringliteral, it must be doubled. The\\
escape sequence denotes a singlebackslash character:
>>>print('C:\\Program Files')C:\Program Files
Similarly, the\'
and\"
sequences denote the single and doublequote character, respectively:
>>>print('\' and\"')' and "
2.5.4.3.Octal character¶
The sequence\ooo
denotes acharacter with the octal (base 8)valueooo:
>>>'\120''P'
Up to three octal digits (0 through 7) are accepted.
In a bytes literal,character means abyte with the given value.In a string literal, it means a Unicode character with the given value.
Changed in version 3.11:Octal escapes with value larger than0o377
(255) produce aDeprecationWarning
.
Changed in version 3.12:Octal escapes with value larger than0o377
(255) produce aSyntaxWarning
.In a future Python version they will raise aSyntaxError
.
2.5.4.4.Hexadecimal character¶
The sequence\xhh
denotes acharacter with the hex (base 16)valuehh:
>>>'\x50''P'
Unlike in Standard C, exactly two hex digits are required.
In a bytes literal,character means abyte with the given value.In a string literal, it means a Unicode character with the given value.
2.5.4.5.Named Unicode character¶
The sequence\N{name}
denotes a Unicode characterwith the givenname:
>>>'\N{LATIN CAPITAL LETTER P}''P'>>>'\N{SNAKE}''🐍'
This sequence cannot appear inbytes literals.
Changed in version 3.3:Support forname aliaseshas been added.
2.5.4.6.Hexadecimal Unicode characters¶
These sequences\uxxxx
and\Uxxxxxxxx
denote theUnicode character with the given hex (base 16) value.Exactly four digits are required for\u
; exactly eight digits arerequired for\U
.The latter can encode any Unicode character.
>>>'\u1234''ሴ'>>>'\U0001f40d''🐍'
These sequences cannot appear inbytes literals.
2.5.4.7.Unrecognized escape sequences¶
Unlike in Standard C, all unrecognized escape sequences are left in the stringunchanged, that is,the backslash is left in the result:
>>>print('\q')\q>>>list('\q')['\\', 'q']
Note that for bytes literals, the escape sequences only recognized in stringliterals (\N...
,\u...
,\U...
) fall into the category ofunrecognized escapes.
Changed in version 3.6:Unrecognized escape sequences produce aDeprecationWarning
.
Changed in version 3.12:Unrecognized escape sequences produce aSyntaxWarning
.In a future Python version they will raise aSyntaxError
.
2.5.5.Bytes literals¶
Bytes literals are always prefixed with ‘b
’ or ‘B
’; they produce aninstance of thebytes
type instead of thestr
type.They may only contain ASCII characters; bytes with a numeric value of 128or greater must be expressed with escape sequences (typicallyHexadecimal character orOctal character):
>>>b'\x89PNG\r\n\x1a\n'b'\x89PNG\r\n\x1a\n'>>>list(b'\x89PNG\r\n\x1a\n')[137, 80, 78, 71, 13, 10, 26, 10]
Similarly, a zero byte must be expressed using an escape sequence (typically\0
or\x00
).
2.5.6.Raw string literals¶
Both string and bytes literals may optionally be prefixed with a letter ‘r
’or ‘R
’; such constructs are calledraw string literalsandraw bytes literals respectively and treat backslashes asliteral characters.As a result, in raw string literals,escape sequencesare not treated specially:
>>>r'\d{4}-\d{2}-\d{2}''\\d{4}-\\d{2}-\\d{2}'
Even in a raw literal, quotes can be escaped with a backslash, but thebackslash remains in the result; for example,r"\""
is a valid stringliteral 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 ofbackslashes). Specifically,a raw literal cannot end in a single backslash(since the backslash would escape the following quote character). Note alsothat a single backslash followed by a newline is interpreted as those twocharacters as part of the literal,not as a line continuation.
2.5.7.f-strings¶
Added in version 3.6.
Aformatted string literal orf-string is a string literalthat is prefixed with ‘f
’ or ‘F
’. These strings may containreplacement fields, which are expressions delimited by curly braces{}
.While other string literals always have a constant value, formatted stringsare really expressions evaluated at run time.
Escape sequences are decoded like in ordinary string literals (except whena literal is also marked as a raw string). After decoding, the grammarfor the contents of the string is:
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
|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 replacedwith the corresponding single curly brace. A single opening curlybracket'{'
marks a replacement field, which starts with aPython expression. To display both the expression text and its value afterevaluation, (useful in debugging), an equal sign'='
may be added after theexpression. A conversion field, introduced by an exclamation point'!'
mayfollow. 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 regularPython expressions surrounded by parentheses, with a few exceptions.An empty expression is not allowed, and bothlambda
andassignment expressions:=
must be surrounded by explicit parentheses.Each expression is evaluated in the context where the formatted string literalappears, in order from left to right. Replacement expressions can containnewlines in both single-quoted and triple-quoted f-strings and they can containcomments. Everything that comes after a#
inside a replacement fieldis a comment (even closing braces and quotes). In that case, replacement fieldsmust be closed in a different line.
>>> f"abc{a # This is a comment }"... + 3}"'abc5'
Changed in version 3.7:Prior to Python 3.7, anawait
expression and comprehensionscontaining anasyncfor
clause were illegal in the expressionsin 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 replacementfields.
When the equal sign'='
is provided, the output will have the expressiontext, the'='
and the evaluated value. Spaces after the opening brace'{'
, within the expression and after the'='
are all retained in theoutput. By default, the'='
causes therepr()
of the expression to beprovided, unless there is a format specified. When a format is specified itdefaults to thestr()
of the expression unless a conversion'!r'
isdeclared.
Added in version 3.8:The equal sign'='
.
If a conversion is specified, the result of evaluating the expressionis converted before formatting. Conversion'!s'
callsstr()
onthe result,'!r'
callsrepr()
, and'!a'
callsascii()
.
The result is then formatted using theformat()
protocol. Theformat specifier is passed to the__format__()
method of theexpression or conversion result. An empty string is passed when theformat specifier is omitted. The formatted result is then included inthe final value of the whole string.
Top-level format specifiers may include nested replacement fields. These nestedfields may include their own conversion fields andformat specifiers, but may not include more deeply nested replacement fields. Theformat specifier mini-language is the same as that used bythestr.format()
method.
Formatted string literals may be concatenated, but replacement fieldscannot be split across literals.
Some examples of formatted string literals:
>>>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 ispermitted:
>>>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-stringinside a replacement field was not possible.
Backslashes are also allowed in replacement fields and are evaluated the sameway as in any other context:
>>>a=["a","b","c"]>>>print(f"List a contains:\n{"\n".join(a)}")List a contains:abc
Changed in version 3.12:Prior to Python 3.12, backslashes were not permitted inside an f-stringreplacement field.
Formatted string literals cannot be used as docstrings, even if they do notinclude expressions.
>>>deffoo():...f"Not a docstring"...>>>foo.__doc__isNoneTrue
See alsoPEP 498 for the proposal that added formatted string literals,andstr.format()
, which uses a related format string mechanism.
2.5.8.t-strings¶
Added in version 3.14.
Atemplate string literal ort-string is a string literalthat is prefixed with ‘t
’ or ‘T
’.These strings follow the same syntax and evaluation rules asformatted string literals, with the following differences:
Rather than evaluating to a
str
object, template string literals evaluateto astring.templatelib.Template
object.The
format()
protocol is not used.Instead, the format specifier and conversions (if any) are passed toa newInterpolation
object that is createdfor each evaluated expression.It is up to code that processes the resultingTemplate
object to decide how to handle format specifiers and conversions.Format specifiers containing nested replacement fields are evaluated eagerly,prior to being passed to the
Interpolation
object.For instance, an interpolation of the form{amount:.{precision}f}
willevaluate the inner expression{precision}
to determine the value of theformat_spec
attribute.Ifprecision
were to be2
, the resulting format specifierwould be'.2f'
.When the equals sign
'='
is provided in an interpolation expression,the text of the expression is appended to the literal string that precedesthe relevant interpolation.This includes the equals sign and any surrounding whitespace.TheInterpolation
instance for the expression will be created asnormal, except thatconversion
willbe set to ‘r
’ (repr()
) by default.If an explicit conversion or format specifier are provided,this will override the default behaviour.
2.6.Numeric literals¶
NUMBER
tokens represent numeric literals, of which there arethree types: integers, floating-point numbers, and imaginary numbers.
NUMBER:integer
|floatnumber
|imagnumber
The numeric value of a numeric literal is the same as if it were passed as astring to theint
,float
orcomplex
classconstructor, respectively.Note that not all valid inputs for those constructors are also valid literals.
Numeric literals do not include a sign; a phrase like-1
isactually an expression composed of the unary operator ‘-
’ and the literal1
.
2.6.1.Integer literals¶
Integer literals denote whole numbers. For example:
732147483647
There is no limit for the length of integer literals apart from what can bestored in available memory:
7922816251426433759354395033679228162514264337593543950336
Underscores can be used to group digits for enhanced readability,and are ignored for determining the numeric value of the literal.For example, the following literals are equivalent:
100_000_000_0001000000000001_00_00_00_00_000
Underscores can only occur between digits.For example,_123
,321_
, and123__321
arenot valid literals.
Integers can be specified in binary (base 2), octal (base 8), or hexadecimal(base 16) using the prefixes0b
,0o
and0x
, respectively.Hexadecimal digits 10 through 15 are represented by lettersA
-F
,case-insensitive. For example:
0b1001101110b_1110_01010o1770o3770xdeadbeef0xDead_Beef
An underscore can follow the base specifier.For example,0x_1f
is a valid literal, but0_x1f
and0x__1f
arenot.
Leading zeros in a non-zero decimal number are not allowed.For example,0123
is not a valid literal.This is for disambiguation with C-style octal literals, which Python usedbefore version 3.0.
Formally, integer literals are described by the following lexical definitions:
integer:decinteger
|bininteger
|octinteger
|hexinteger
|zerointeger
decinteger:nonzerodigit
(["_"]digit
)*bininteger:"0" ("b" |"B") (["_"]bindigit
)+octinteger:"0" ("o" |"O") (["_"]octdigit
)+hexinteger:"0" ("x" |"X") (["_"]hexdigit
)+zerointeger:"0"+ (["_"]"0")*nonzerodigit:"1"..."9"digit:"0"..."9"bindigit:"0" |"1"octdigit:"0"..."7"hexdigit:digit
|"a"..."f" |"A"..."F"
Changed in version 3.6:Underscores are now allowed for grouping purposes in literals.
2.6.2.Floating-point literals¶
Floating-point (float) literals, such as3.14
or1.5
, denoteapproximations of real numbers.
They consist ofinteger andfraction parts, each composed of decimal digits.The parts are separated by a decimal point,.
:
2.718284.0
Unlike in integer literals, leading zeros are allowed in the numeric parts.For example,077.010
is legal, and denotes the same number as77.10
.
As in integer literals, single underscores may occur between digits to helpreadability:
96_485.332_1233.14_15_93
Either of these parts, but not both, can be empty. For example:
10.# (equivalent to 10.0).001# (equivalent to 0.001)
Optionally, the integer and fraction may be followed by anexponent:the lettere
orE
, followed by an optional sign,+
or-
,and a number in the same format as the integer and fraction parts.Thee
orE
represents “times ten raised to the power of”:
1.0e3# (represents 1.0×10³, or 1000.0)1.166e-5# (represents 1.166×10⁻⁵, or 0.00001166)6.02214076e+23# (represents 6.02214076×10²³, or 602214076000000000000000.)
In floats with only integer and exponent parts, the decimal point may beomitted:
1e3# (equivalent to 1.e3 and 1.0e3)0e0# (equivalent to 0.)
Formally, floating-point literals are described by the followinglexical definitions:
floatnumber: |digitpart
"." [digitpart
] [exponent
] |"."digitpart
[exponent
] |digitpart
exponent
digitpart:digit
(["_"]digit
)*exponent: ("e" |"E") ["+" |"-"]digitpart
Changed in version 3.6:Underscores are now allowed for grouping purposes in literals.
2.6.3.Imaginary literals¶
Python hascomplex number objects, but no complexliterals.Instead,imaginary literals denote complex numbers with a zeroreal part.
For example, in math, the complex number 3+4.2i is writtenas the real number 3 added to the imaginary number 4.2i.Python uses a similar syntax, except the imaginary unit is written asj
rather thani:
3+4.2j
This is an expression composedof theinteger literal3
,theoperator ‘+
’,and theimaginary literal4.2j
.Since these are three separate tokens, whitespace is allowed between them:
3+4.2j
No whitespace is allowedwithin each token.In particular, thej
suffix, may not be separated from the numberbefore it.
The number before thej
has the same syntax as a floating-point literal.Thus, the following are valid imaginary literals:
4.2j3.14j10.j.001j1e100j3.14e-10j3.14_15_93j
Unlike in a floating-point literal the decimal point can be omitted if theimaginary number only has an integer part.The number is still evaluated as a floating-point number, not an integer:
10j0j1000000000000000000000000j# equivalent to 1e+24j
Thej
suffix is case-insensitive.That means you can useJ
instead:
3.14J# equivalent to 3.14j
Formally, imaginary literals are described by the following lexical definition:
imagnumber: (floatnumber
|digitpart
) ("j" |"J")
2.7.Operators and delimiters¶
The following grammar definesoperator anddelimiter tokens,that is, the genericOP
token type.Alist of these tokens and their namesis also available in thetoken
module documentation.
OP: | assignment_operator | bitwise_operator | comparison_operator | enclosing_delimiter | other_delimiter | arithmetic_operator |"..." | other_opassignment_operator:"+=" |"-=" |"*=" |"**=" |"/=" |"//=" |"%=" |"&=" |"|=" |"^=" |"<<=" |">>=" |"@=" |":="bitwise_operator:"&" |"|" |"^" |"~" |"<<" |">>"comparison_operator:"<=" |">=" |"<" |">" |"==" |"!="enclosing_delimiter:"(" |")" |"[" |"]" |"{" |"}"other_delimiter:"," |":" |"!" |";" |"=" |"->"arithmetic_operator:"+" |"-" |"**" |"*" |"//" |"/" |"%"other_op:"." |"@"
Note
Generally,operators are used to combineexpressions,whiledelimiters serve other purposes.However, there is no clear, formal distinction between the two categories.
Some tokens can serve as either operators or delimiters, depending on usage.For example,*
is both the multiplication operator and a delimiter usedfor sequence unpacking, and@
is both the matrix multiplication anda delimiter that introduces decorators.
For some tokens, the distinction is unclear.For example, some people consider.
,(
, and)
to be delimiters, while otherssee thegetattr()
operator and the function call operator(s).
Some of Python’s operators, likeand
,or
, andnotin
, usekeyword tokens rather than “symbols” (operator tokens).
A sequence of three consecutive periods (...
) has a specialmeaning as anEllipsis
literal.