The tokeniser reads the decoded text (see File structure) and turns it into a stream of tokens for the parser. The tokens are NEWLINE, INDENT, DEDENT, names, keywords, literals, operators, delimiters and the end marker. Comments and most white space are dropped on the way. This page follows chapter 2 of the Language Reference.
Line structure
A program is divided into logical lines, each ending in a NEWLINE token. A logical line is made of one or more physical lines, which are the lines as stored in the file (2.1.1, 2.1.2). A statement cannot cross a logical line except where the grammar allows NEWLINE, as between the statements of a compound statement.
Physical lines
A physical line ends in LF, CR LF or CR. Each form is replaced by a single LF before anything else happens, even inside string literals, and a file may mix them. The end of the input also ends the last line.
Comments
A comment starts with # outside a string literal and runs to the end of
the physical line (2.1.3). It ends the logical line unless the line is inside
brackets. Python has no block comment. A
coding declaration and a
shebang are comments with a
special use.
Joining lines
Explicit joining (2.1.5): a physical line that ends in a backslash outside a string or comment is joined to the next, and the backslash and line end are removed. A line ending in a backslash cannot carry a comment, and the backslash cannot split a token other than a string literal.
Implicit joining (2.1.6): inside ( ),
[ ] or { }, lines join without a backslash. These lines may
carry comments, may be blank, and may be indented freely, and no NEWLINE token is
produced between them. This is the preferred way to split a long line.
total = (first_value # implicit joining: brackets
+ second_value
+ third_value)
if year > 1900 and year < 2100 \
and month <= 12: # explicit joining: backslash
print("in range")
Blank lines
A logical line with only spaces, tabs, form feeds and possibly a comment is ignored and produces no NEWLINE (2.1.7). In the interactive prompt a blank line can end a block, but this is a feature of the prompt.
Indentation
The white space at the start of a logical line sets its indentation level, and indentation is what groups statements (2.1.8). Tabs are replaced, from left to right, by one to eight spaces so the column reaches the next multiple of eight. The total count of spaces is the level. A form feed at the start of a line is ignored for this count.
The tokeniser keeps a stack of levels, starting with a single 0 that is never removed. For each logical line that is not blank, the level is compared with the top of the stack:
- If it is equal, nothing happens.
- If it is larger, it is pushed and one INDENT token is generated.
- If it is smaller, it must be a value already on the stack. Every larger value is popped, and one DEDENT token is generated for each.
- At the end of the file, one DEDENT is generated for each value on the stack above 0.
def f(x):
if x:
return 1
return 0
NAME 'def' NAME 'f' OP '(' NAME 'x' OP ')' OP ':' NEWLINE
INDENT NAME 'if' NAME 'x' OP ':' NEWLINE
INDENT NAME 'return' NUMBER '1' NEWLINE
DEDENT NAME 'return' NUMBER '0' NEWLINE
DEDENT ENDMARKER
The compiler reports these errors:
| Problem | Error |
|---|---|
| A level that is not on the stack | IndentationError: unindent does not match any outer indentation level |
| An indented line where a statement cannot be indented | IndentationError: unexpected indent |
| Tabs and spaces mixed so the meaning depends on the width of a tab | TabError: inconsistent use of tabs and spaces in indentation |
Convention (PEP 8) is four spaces per level and no tabs.
Space between tokens
Except at the start of a logical line and inside string literals, spaces, tabs and
form feeds separate tokens and are otherwise ignored (2.1.9). White space is needed
between two tokens only when joining them would read as one, as with
if x. A number directly followed by a keyword, as in 1or
2, still works but raises SyntaxWarning, and a future version
will reject it.
Names
Names, also called identifiers, are used for variables, functions, classes, modules and attributes (2.3). The lexical rule is:
NAME: name_start name_continue*
name_start: "a"..."z" | "A"..."Z" | "_" | <non-ASCII character>
name_continue: name_start | "0"..."9"
identifier: <NAME, except keywords>
- A name has no length limit, and case matters.
- A non-ASCII name must start with a
xid_startcharacter and continue withxid_continuecharacters, which are the letter-like and digit-like sets from Unicode (2.3.4, PEP 3131).ř_1and蛇are valid;€is not. - Names are converted to Unicode normalisation form NFKC while parsing. Two names
that normalise to the same text are the same name. This happens in the source only:
getattr(obj, "fi")does not normalise its argument.
Keywords
There are 35 keywords, which can never be used as names (2.3.1):
| Group | Keywords |
|---|---|
| Constants | True False None |
| Logic and tests | and or not in is |
| Selection | if elif else |
| Loops | for while break continue |
| Definitions | def class lambda return yield |
| Asynchronous | async await |
| Exceptions | try except finally raise assert |
| Context managers | with as |
| Modules | import from |
| Scope | global nonlocal |
| Other | pass del |
In alphabetical order, as the keyword module lists them:
False None True and as assert async await break class continue def del elif
else except finally for from global if import in is lambda nonlocal not or pass raise
return try while with yield.
Soft keywords
A few words are keywords only in one place, and ordinary names elsewhere, so old code that uses them as names keeps working (2.3.2):
| Word | Keyword when | Since |
|---|---|---|
match, case, _ | In a match statement | 3.10 |
type | Starting a type statement | 3.12 |
lazy | Directly before import or from | 3.15 |
__debug__ cannot be assigned to, although it is not a keyword.
Reserved classes of names
Some names have a special meaning by their pattern of underscores (2.3.3):
| Form | Meaning |
|---|---|
_* | Not imported by from module import * |
_ | In a case pattern it is the wildcard. At the interactive prompt it holds the last result. Elsewhere it is an ordinary name, often used for an unused value |
__*__ | Defined by the interpreter and the standard library, such as __init__ and __name__. Other uses may break without warning |
__* | Inside a class, a class-private name that is rewritten to avoid clashes |
Numeric literals
Numeric literals carry no sign: -1 is the unary operator and the literal
1 (2.6). Single underscores may appear between digits, and after a base
prefix, for grouping (PEP 515, Python 3.6).
Integers
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")*
| Base | Prefix | Example | Value |
|---|---|---|---|
| Decimal | none | 255 | 255 |
| Hexadecimal | 0x or 0X | 0xFF | 255 |
| Octal | 0o or 0O | 0o377 | 255 |
| Binary | 0b or 0B | 0b1111_1111 | 255 |
- Integers have unlimited precision, so a literal can be as long as memory allows.
0123is an error, to avoid confusion with the C-style octal of Python 2. A number made only of zeros, such as00or0_0, is valid.1__0,_1and1_are errors._1is a valid name, not a number.
Floating-point numbers
floatnumber:
digitpart "." [digitpart] [exponent]
| "." digitpart [exponent]
| digitpart exponent
digitpart: digit (["_"] digit)*
exponent: ("e" | "E") ["+" | "-"] digitpart
Valid examples are 3.14, 10., .001,
1e100, 3.14e-10 and 0e0. Leading zeros are
allowed here: 077.010 means 77.01. Underscores are allowed between
digits, as in 96_485.332_123, but not next to the . or the
e. In CPython a float is an IEEE 754 double. There are no
literals for infinity or NaN; use float("inf") and
float("nan").
Imaginary numbers
imagnumber: (floatnumber | digitpart) ("j" | "J")
An imaginary literal has a real part of zero, as in 4.5j or
1_000j. A complex number with a real part is written as a sum:
3+4j. A base prefix cannot be used, so 0xFFj is an error.
String and bytes literals
A string literal is written in matching single or double quotes, and a triple-quoted form runs over any number of lines (2.5). A prefix before the opening quote changes what it means.
| Prefix | Meaning | Result type |
|---|---|---|
none, or u | Normal string. u has no effect and exists for old code (PEP 414) | str |
r | Raw string: backslashes are kept | str |
b | Bytes literal | bytes |
br, rb | Raw bytes literal | bytes |
f | Formatted string | str |
fr, rf | Raw formatted string | str |
t | Template string (3.14) | string.templatelib.Template |
tr, rt | Raw template string | string.templatelib.Template |
Prefixes are case-insensitive, so Rb and bR are valid.
u cannot be combined with anything. b cannot be combined with
f or t, and f cannot be combined with
t.
Triple-quoted strings
A string opened with ''' or """ can contain unescaped
newlines and quotes, and ends at the first matching triple quote. Line endings inside
it are stored as LF. Whitespace is kept exactly. A backslash at the end of a line
skips the line end. Common uses are multi-line text and
docstrings.
Escape sequences
In ordinary and bytes literals, these sequences are recognised (2.5.4):
| Sequence | Meaning |
|---|---|
\ + newline | Ignored: the line continues |
\\, \', \" | Backslash, single quote, double quote |
\a, \b, \f | Bell, backspace, form feed |
\n, \r, \t, \v | Line feed, carriage return, tab, vertical tab |
\ooo | Character with the octal value ooo (up to three digits) |
\xhh | Character with the hex value hh (exactly two digits) |
\N{name} | The Unicode character of that name (strings only) |
\uxxxx | Code point, four hex digits (strings only) |
\Uxxxxxxxx | Code point, eight hex digits (strings only) |
- Python keeps the backslash of any other sequence, so
'\q'is two characters. These unrecognised escapes raise aSyntaxWarningsince Python 3.12 and will be an error in a future version. - In bytes literals
\N,\uand\Uare unrecognised escapes. - An octal escape above
\377also raisesSyntaxWarningsince Python 3.12. - In a string,
\ud800and other surrogates are allowed, although they cannot be encoded to UTF-8 without a special error handler.
Bytes literals
A bytes literal produces bytes, not text (2.5.5). It may contain only
ASCII characters, whatever the source encoding, so byte values of 128 or more must use
an escape.
signature = b'\x89PNG\r\n\x1a\n'
list(signature) # [137, 80, 78, 71, 13, 10, 26, 10]
Raw strings
With an r prefix, a backslash is a plain character and no escapes are
processed (2.5.6). A quote can still follow a backslash, but the backslash stays in
the result: r"\"" is two characters. A raw literal cannot end in an odd
number of backslashes, so r"\" is an error. Raw strings suit regular
expressions and Windows paths.
import re
re.findall(r"\d{4}-\d{2}", "due 2026-11") # ['2026-11']
Concatenation
Adjacent string literals are joined at compile time, even across lines inside brackets (6.2.3.2). Plain strings and f-strings can be mixed. Bytes cannot be mixed with strings, and t-strings cannot be mixed with either.
message = ("first part, "
f"then {value!r}, "
"and the end")
f-strings
A formatted string literal contains replacement fields in braces, and each one is an expression evaluated where the f-string appears (2.5.7, PEP 498, Python 3.6). Doubled braces outside a field stand for a literal brace.
{ expression [ = ] [ !conversion ] [ :format_spec ] }
| Part | Form | Effect |
|---|---|---|
| Debug specifier | = | Writes the expression's text, an equals sign and its value (3.8). It uses repr(), unless a format specifier is given |
| Conversion | !s, !r, !a | Applies str(), repr() or ascii() before formatting |
| Format specifier | :spec | Passed to format(). It can contain nested replacement fields |
name = "Ada"
width = 8
pi = 3.14159
f"Hello, {name}!" # 'Hello, Ada!'
f"{name!r}" # "'Ada'"
f"{pi:.2f}" # '3.14'
f"{name:>{width}}" # ' Ada'
f"{pi=:.3f}" # 'pi=3.142'
f"{255:#x}, {1234567:,}" # '0xff, 1,234,567'
f"{{{name}}}" # '{Ada}'
Since Python 3.12 (PEP 701) the expression inside a field follows the normal rules: it may reuse the f-string's own quote character, contain backslashes and comments, span several lines, and nest f-strings to any depth in CPython.
- An empty expression is an error, and
lambdaand:=must be in parentheses. - Everything after a
#in a field is a comment, including any closing brace, so a field with a comment must close on a later line. - An f-string cannot be a docstring.
t-strings
A template string, or t-string, uses the same syntax as an f-string (2.5.8, PEP 750,
Python 3.14). The difference is what it creates: a
string.templatelib.Template object, which keeps the static text and the
evaluated values apart so that code can process them, for example to escape values
before building HTML.
name = "Ada"
template = t"Hello, {name!r}"
template.strings # ('Hello, ', '')
template.values # ('Ada',)
template.interpolations # (Interpolation('Ada', 'name', 'r', ''),)
Each Interpolation has value, expression,
conversion and format_spec. The conversion and format
specifier are recorded but not applied. A Template can be added to
another Template, but not to a str.
Operators and delimiters
Section 2.7 of the Language Reference lists these tokens. The longest match wins, so
** is one token, never two * tokens. Their meanings and
precedence are on Expressions.
| Group | Tokens |
|---|---|
| Arithmetic | + - ** * // / % @ |
| Bitwise | & | ^ ~ << >> |
| Comparison | <= >= < > == != |
| Assignment | = += -= *= **= /= //= %= &= |= ^= <<= >>= @= := |
| Enclosing delimiters | ( ) [ ] { } |
| Other delimiters | , : ! ; . -> |
| Ellipsis | ... |
! is a token only so that f-string conversions can use it. Alone, it is
not an operator; != is the inequality operator. Python has no
++, --, && or ||: use
x += 1, and and or. $, ?
and the backquote are not tokens in Python.