Book Image

Python Essentials

By : Steven F. Lott
Book Image

Python Essentials

By: Steven F. Lott

Overview of this book

Table of Contents (22 chapters)
Python Essentials
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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 decimal string

  • complex(): Creates complex values from a variety of objects

    • complex(23) creates (23+0j)

    • complex(23, 3) creates (23+3j)

    • complex('23+2j') creates (23+2j)

We can convert single numbers, pairs of numbers, and even some strings into...