IMPORTANT: To view this page as Markdown, append `.md` to the URL (e.g. /docs/manual/basics.md). For the complete Mojo documentation index, see llms.txt.
Skip to main content
Version: Nightly
For the complete Mojo documentation index, see llms.txt. Markdown versions of all pages are available by appending .md to any URL (e.g. /docs/manual/basics.md).

atol

def atol(str_slice: StringSpan, base: Int = Int(10)) -> Int

Parses and returns the given string as an integer in the given base.

If base is set to 0, the string is parsed as an integer literal, with the following considerations:

  • '0b' or '0B' prefix indicates binary (base 2)
  • '0o' or '0O' prefix indicates octal (base 8)
  • '0x' or '0X' prefix indicates hexadecimal (base 16)
  • Without a prefix, it's treated as decimal (base 10)

This follows Python's integer literals format.

This function is in the prelude, so you don't need to import it.

Notes: This function only accepts ASCII digits (0-9 and a-z/A-Z for bases greater than 10). Unicode digit characters are not supported. Leading and trailing whitespace is trimmed, but only ASCII/POSIX whitespace characters are recognized (space, tab, newline, etc.). Unicode whitespace characters will cause a parsing error.

Examples:

>>> atol("32")
32
>>> atol("FF", 16)
255
>>> atol("0xFF", 0)
255
>>> atol("0b1010", 0)
10

Args:

  • ​str_slice (StringSpan): A string to be parsed as an integer in the given base.
  • ​base (Int): Base used for conversion, value must be between 2 and 36, or 0.

Returns:

Int: An integer value that represents the string.

Raises:

If the given string cannot be parsed as an integer value or if an incorrect base is provided.