Using the built-in conversion functions

We have a number of conversion functions in the various types of data we've seen in this chapter. Each of the built-in numeric types has a proper constructor function. As with many Python functions, each of these has a number of different kinds of arguments it can handle:

  • int(): Creates an int from a wide variety of other objects
    • int(3.718) for another number
    • int('48879') for a string in base 10
    • int('beef', 16) for a string in the given base—16 in this example
    • The int() function can ignore the extra prefix characters on numbers written in Python literal syntax: int('0b1010',2), int('0xbeef',16), and int('0o123',8)
  • float(): Creates a float from other objects
    • float(7331) for another number
    • float('4.8879e5') for a ...

Get Python Essentials now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.