π Python Type Casting β Convert Strings, Numbers, Booleans (2025 Guide)
π What is Type Casting in Python?
Type casting (or type conversion) in Python refers to the process of converting a value from one data type to another.
Python provides built-in functions to cast values between compatible types like strings, integers, floats, and more.
β Why Use Type Casting?
- To convert user input (which is a string) into a number
- To ensure correct data types during operations
- To avoid type errors in expressions
π οΈ Common Type Casting Functions
Function | Converts to | Example |
---|---|---|
int(x) | Integer | int("5") β 5 |
float(x) | Float | float("3.14") β 3.14 |
str(x) | String | str(100) β "100" |
bool(x) | Boolean | bool(0) β False , bool("Hi") β True |
list(x) | List | list("abc") β ['a','b','c'] |
tuple(x) | Tuple | tuple([1,2]) β (1,2) |
βοΈ Examples
x = "10"
y = int(x) # Convert string to integer
print(y + 5) # Output: 15
z = float("5.6") # Convert string to float
a = str(42) # Convert number to string
β οΈ Invalid Casting
Not all conversions are possible:
int("hello") # β ValueError: invalid literal
Always ensure the string or data can be safely converted.
π Summary β Python Type Casting
From β To | Function | Example |
---|---|---|
String β Int | int("123") | 123 |
String β Float | float("3.14") | 3.14 |
Number β Str | str(50) | “50” |
Any β Bool | bool(x) | False if x is 0, '' , None |
β FAQs β Python Type Casting
β What is type casting in Python?
Type casting is the process of converting a value from one data type to another, like converting a string to an integer or a float to a string.
β What are the common type casting functions in Python?
int()
β converts to integerfloat()
β converts to floatstr()
β converts to stringbool()
β converts to booleanlist()
β converts to listtuple()
β converts to tuple
β Can I convert a string to a number?
Yes, if the string is numeric:
int("123") # 123
float("3.14") # 3.14
β Non-numeric strings will raise a ValueError
.
β What does bool()
return for different values?
bool(0)
,bool("")
,bool(None)
βFalse
- All other values β
True
β Whatβs the difference between str(123)
and "123"
?
Both result in the same string, but:
"123"
is a hardcoded stringstr(123)
is type casting from a number to a string dynamically
Share Now :