Converting Between Types

We've seen several Python types, including int, float, and str.

In [1]:
type(42)
Out[1]:
int
In [2]:
type(3.14)
Out[2]:
float
In [3]:
type('Hello')
Out[3]:
str

We can convert values from one type to another. For example, we conver two strs to numeric values:

In [4]:
int('45')
Out[4]:
45
In [5]:
float('3.14')
Out[5]:
3.14

Converting that str value to type float allows us to perform arithmetic operations on it, such as:

In [6]:
float('3.14') / 2
Out[6]:
1.57

If we try to convert a str that can't be represented as a float, an error will occur:

In [7]:
float("forty-two")
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-7-f991ea6ec533> in <module>()
----> 1 float("forty-two")

ValueError: could not convert string to float: 'forty-two'

Converting floats to string makes sense if, for example, we want to use "string addition":

Floats and strings can be converted to integers:

In [8]:
int(3.14)
Out[8]:
3

Notice that integers are truncated rather than rounded:

In [2]:
int(3.75)
Out[2]:
3
In [10]:
int("42")
Out[10]:
42

As we saw earlier, not all values can be converted from one type to another. In this case a the str 42.3 cannot be converted to an int:

In [11]:
int("42.3")
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-11-6076aa6f9770> in <module>()
----> 1 int("42.3")

ValueError: invalid literal for int() with base 10: '42.3'

Doesn't work: the string must contain an integer to be converted. But we have the tools to do this: