Type Conversion
We use type names to convert from one type to another. Below are some examples of type conversions and their resulting values.
[1]:
print("boolean conversions")
print("-------------------------------------------------------------")
print("int(True) -> " + str(int(True)) + " # bool to int")
print("float(False) -> " + str(float(False)) + " # bool to float")
print("str(True) -> '" + str(True) + "' # bool to str")
print("\ninteger conversions")
print("-------------------------------------------------------------")
print("bool(1) -> " + str(bool(1)) + " # int to bool")
print("float(1234567) -> " + str(float(1234567)) + " # int to float")
print("str(1234567) -> '" + str(1234567) + "' # int to str")
print("\nfloat conversions")
print("-------------------------------------------------------------")
print("bool(1.0) -> " + str(bool(1.0)) + " # float to bool")
print("int(3.99) -> " + str(int(3.99)) + " # float to int")
print("int(-3.99) -> " + str(int(-3.99)) + " # negative float to int")
print("str(3.99) -> '" + str(3.99) + "' # float to str")
print("\nstring conversions")
print("-------------------------------------------------------------")
print("bool('False') -> " + str(bool('False')) + " # str to bool")
print("int('1234567') -> " + str(int('1234567')) + " # str to int")
print("float('1234567') -> " + str(float('1234567')) + " # str to float")
print("\nascii conversions")
print("-------------------------------------------------------------")
print("ord('A') -> " + str(ord('A')) + " # str to ascii")
print("chr(122) -> '" + str(chr(122)) + "' # ascii to str")
boolean conversions
-------------------------------------------------------------
int(True) -> 1 # bool to int
float(False) -> 0.0 # bool to float
str(True) -> 'True' # bool to str
integer conversions
-------------------------------------------------------------
bool(1) -> True # int to bool
float(1234567) -> 1234567.0 # int to float
str(1234567) -> '1234567' # int to str
float conversions
-------------------------------------------------------------
bool(1.0) -> True # float to bool
int(3.99) -> 3 # float to int
int(-3.99) -> -3 # negative float to int
str(3.99) -> '3.99' # float to str
string conversions
-------------------------------------------------------------
bool('False') -> True # str to bool
int('1234567') -> 1234567 # str to int
float('1234567') -> 1234567.0 # str to float
ascii conversions
-------------------------------------------------------------
ord('A') -> 65 # str to ascii
chr(122) -> 'z' # ascii to str
Not all values are compatible. To convert a string to a number type, the string must be all numbers.
[1]:
ok_to_convert = "987654321"
int(ok_to_convert)
not_ok_to_convert = "abcdefghijklmnopqrstuvwxyz"
# int(not_ok_to_convert) # Value Error
Only the empty string converts to False
[14]:
print(bool('0'))
print(bool('False'))
print(bool(''))
True
True
False
You can convert '0'
to False
with a nested operation
[15]:
print(bool('0'))
print(bool(int('0')))
True
False