Numbers and Strings

Learn about the different categories that fall under the numbers and strings section in Python.

Introduction to numbers

There are several different kinds of numbers in Python. The following describes all of these:

  • A decimal integer consists of either the number 0 or a sequence of digits not beginning with 0.
  • A binary integer consists of binary digits (0, 1), beginning with 0b or 0B.
  • An octal integer consists of a sequence of octal digits (0 to 7), beginning with 0o or 0O.
  • A hexadecimal integer consists of a sequence of hex digits (0 to 9 and a to f or A to F), beginning with 0x or 0X.
  • A floating-point (“real”) number includes a decimal point, an exponent suffix, or both. The exponent consists of an optional sign, the letter e or E, and one or more digits.
  • An imaginary number consists of a decimal integer or a floating-point number, and it is suffixed by j (not i) or J.
  • A complex number consists of the sum or difference of an integer or floating-point number and an imaginary number.

Introduction to strings

Similar to numbers, a string can also be represented in various ways in Python. The following describes all of these:

A string is a sequence of zero or more characters, enclosed in single quotes ('...'), double quotes ("..."), triple single quotes ('''...'''), or triple double quotes ("""..."""). It can be treated as a sequence of characters.

Triple-quoted strings may extend across several lines, and include the line breaks as part of the string, unless the line break is immediately preceded by a backslash (\).

A raw string is a string prefixed with r or R. In a raw string, the backslash does not escape characters; all characters stand for themselves. This is especially useful when writing regular expressions.

Regular expressions in Python follow the POSIX standards and are usually written as raw strings. They will not be covered here.

The eval(string) evaluates string as a Python expression and returns the result. If you use this, be sure string does not contain malicious code.

Formatting strings

There are three ways to format a string: f-strings, the format method, and the old-style % formatting. Generally, the f-string method is recommended.

Using f-strings

A formatted string, or f-string, is prefixed with f or F. In an f-string, any expression surrounded by braces, {}, is replaced by its value. Here’s an example of this:

Get hands-on with 1200+ tech skills courses.