Python Casting
Python Casting
In type casting, data loss may occur because we enforce the object to a
specific data type.
flag_true = True
flag_false = False
print(type(flag_true))
# Output class 'bool'
string_num = "225"
print(type(string_num))
# Output class 'str'
AD
When converting string type to int type, a string must contain integral value
only and should be base-10. If you try to convert
Example
# ValueError: invalid literal for int() with base 10: 'Score is 25'
num = int(string_num)
print(num)
num = 725
print(type(num))
# Output class 'int'
AD
Casting Boolean to float
flag_true = True
flag_false = False
print(type(flag_true))
# Output class 'bool'
string_num = "725.535"
print(type(string_num))
# Output class 'str'
AD
The complex function has the following two forms for conversion.
r_num = 135
print(type(r_num)) # class 'int'
AD
r_num = 53.250
print(type(r_num)) # class 'float'
AD
boolean_true = True
print(type(boolean_true)) # class 'bool'
AD
num1 = 10
num2 = 0
print(type(num1)) # class 'int'
print(b1)
# Output True
print(b2)
# Output False
print(type(b1))
# class 'bool'
AD
f_num1 = 25.35
f_num2 = 0.0
print(type(f_num1)) # class 'float'
print(b1)
# Output True
print(b2)
# Output False
print(type(b1))
# Output class 'bool'
AD
Casting string to Boolean type
s1 = "False"
s2 = "True"
s3 = "812"
s4 = ""
print(type(s1)) # class 'str'
print(b1) # True
print(b2) # True
print(b3) # True
print(b4) # False
print(type(b1)) # class 'bool'
AD
c1 = 33 + 9j
c2 = 0 + 0j
print(type(c1)) # class 'complex'
print(b1) # True
print(b2) # False
print(type(b1)) # class 'bool'
num = 15
print(type(num)) # class 'int'
AD
num = 75.35
print(type(num)) # class 'float'
complex_num = 15 + 5j
print(type(complex_num)) # class 'complex'
print(type(s1))
# class 'str'
Casting bool type to str type
AD
b1 = True
b2 = False
print(type(b1)) # class 'bool'