✍️ Python Syntax & Basic Constructs
Estimated reading: 2 minutes 26 views

πŸ”„ 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

FunctionConverts toExample
int(x)Integerint("5") β†’ 5
float(x)Floatfloat("3.14") β†’ 3.14
str(x)Stringstr(100) β†’ "100"
bool(x)Booleanbool(0) β†’ False, bool("Hi") β†’ True
list(x)Listlist("abc") β†’ ['a','b','c']
tuple(x)Tupletuple([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 β†’ ToFunctionExample
String β†’ Intint("123")123
String β†’ Floatfloat("3.14")3.14
Number β†’ Strstr(50)“50”
Any β†’ Boolbool(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 integer
  • float() β†’ converts to float
  • str() β†’ converts to string
  • bool() β†’ converts to boolean
  • list() β†’ converts to list
  • tuple() β†’ 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 string
  • str(123) is type casting from a number to a string dynamically

Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

Python Type Casting

Or Copy Link

CONTENTS
Scroll to Top