We've seen several Python types, including int
, float
, and str
.
type(42)
type(3.14)
type('Hello')
We can convert values from one type to another. For example, we conver two str
s to numeric values:
int('45')
float('3.14')
Converting that str
value to type float
allows us to perform arithmetic operations on it, such as:
float('3.14') / 2
If we try to convert a str
that can't be represented as a float
, an error will occur:
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:
int(3.14)
Notice that integers are truncated rather than rounded:
int(3.75)
int("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
:
int("42.3")
Doesn't work: the string must contain an integer to be converted. But we have the tools to do this: