Skip to main content

Mojo literals reference

A literal is a value written directly in source code: 42, "hello", True. Literals produce values without reading variables or calling functions. Each section below covers one literal type, its syntax, and any rules the lexer enforces.

Integer literals

Integer literals represent whole numbers in four bases:

42        # Decimal
0xFF      # Hexadecimal (0x or 0X prefix)
0o52      # Octal (0o or 0O prefix)
0b101010  # Binary (0b or 0B prefix)

Integer literals follow these lexical rules:

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)+

Integer literals are always non-negative. -1024 is the unary negation operator - applied to the literal 1024.

Underscores can appear between digits for readability. Mojo is more permissive than Python here. Consecutive and trailing underscores are allowed:

1_000_000  # Readable grouping
1__000_    # Also valid (consecutive and trailing underscores OK)

Leading zeros in decimal literals are not allowed. Use the 0o prefix for octal:

0123   # Error: leading zeros in decimal integer literals are not permitted
0o123  # OK: octal

A base prefix must be followed by at least one digit:

0x  # Error: no digits specified for hex literal
0b  # Error: no digits specified for binary literal
0o  # Error: no digits specified for octal literal

Floating-point literals

Floating-point literals represent numbers with a fractional or exponent part:

1.0
3.14159
.5       # Fraction only (no integer part)
2.       # Integer part with decimal point
2.5e-3   # With exponent
1E10     # Capital E works too

Floating-point literals follow these lexical rules:

floatnumber   → pointfloat | exponentfloat
pointfloat    → digitpart? fraction | digitpart "."
exponentfloat → (digitpart | pointfloat) exponent
fraction      → "." digitpart
exponent      → ("e" | "E") ("+" | "-")? digitpart
digitpart     → digit ("_" | digit)*

Floating-point literals are always non-negative. -3.14 is the unary negation operator - applied to the literal 3.14.

When included, an exponent marker (e or E) must be followed by at least one digit:

2.5e    # Error: expecting a digit after the exponent
2.5e-   # Error: expecting a digit after the exponent
2.5e-3  # OK

Underscores in floating-point literals work as they do in integers. Place them anywhere that enhances readability:

1_000.000_5

String literals

String literals represent text values. Mojo supports single and double quotes, and a triple-quote form for multi-line strings:

"Hello"
'world'
"""Multi-line
string"""
'''Also
multi-line'''

String literals on adjacent lines are joined into a single string. This works on one line or across lines when the continuation is indented:

"Hello, " "World"        # "Hello, World"

x = "line one "
    "line two"           # "line one line two" (indented continuation)

Prefix with r or R to create a raw string that disables escape processing:

r"C:\path\to\file"  # Backslashes treated literally

Escape sequences

Mojo recognizes these escape sequences in non-raw string literals:

SequenceMeaningSequenceMeaning
\\Backslash\aBell
\"Double quote\bBackspace
\'Single quote\fForm feed
\nNewline\vVertical tab
\rCarriage return\xHHHex value (exactly 2 hex digits)
\tTab\0\377Octal value (1–3 octal digits)

A backslash at the end of a line inside a triple-quoted string suppresses the newline, joining the next line directly:

x = """\
    This string has no leading newline.\
    """

T-string literals

T-string literals support expression interpolation using {}:

name = "World"
t"Hello, {name}!"   # "Hello, World!"
t"1 + 1 = {1 + 1}"  # "1 + 1 = 2"

Expressions inside {} are evaluated at runtime. Adjacent t-string literals are joined, just like regular string literals.

T-strings can be triple-quoted and combined with the raw prefix (rt, tr, rT, tR):

t"""
Hello, {name}!
"""

rt"Path: {base}\subdir"  # Raw t-string: backslashes are literal

Use {{ and }} to include literal braces in a t-string:

t"Use {{braces}} in t-strings"  # "Use {braces} in t-strings"

T-strings can be nested. An interpolation expression can itself contain t-strings, up to 20 levels deep.

Boolean literals

True and False represent boolean truth values.

x = True
y = False

None literal

None represents the absence of a value. It is the only value of type NoneType.

x: NoneType = None

A function without an explicit return type returns None. These two declarations are equivalent:

def greet():
    print("hello")

def greet() -> None:
    print("hello")

Self literal

Self refers to the enclosing type inside a struct or trait definition:

struct Point:
    var x: Float64
    var y: Float64

    def create() -> Self:          # Self refers to Point
        return Self(0.0, 0.0)

    def distance(self) -> Float64: # self is an argument name, not Self
        return (self.x ** 2 + self.y ** 2).sqrt()

Self (capital S) is a keyword that refers to the type. self (lowercase) is a conventional argument name for the instance.

Discard pattern

The underscore _ discards a value in an assignment:

_, y = get_pair()  # Ignore the first element

Ellipsis literal

... marks a trait method as required. Conforming types must provide their own implementation. It is only valid inside trait definitions:

trait Drawable:
    def draw(self) -> None: ...   # Required: conforming types must implement

... and pass are not interchangeable. pass is a no-op statement that provides an empty body. ... is a requirement marker that means "you must implement this."

Was this page helpful?