Python Casting

Learn how to convert between different data types in Python using casting.

Specify a Variable Type

There may be times when you want to specify a type on to a variable. This can be done with casting. Python is an object-orientated language, and as such it uses classes to define data types, including its primitive types.

Casting in Python is therefore done using constructor functions:

  • int() - constructs an integer number from an integer literal, a float literal (by removing all decimals), or a string literal (providing the string represents a whole number)
  • float() - constructs a float number from an integer literal, a float literal or a string literal (providing the string represents a float or an integer)
  • str() - constructs a string from a wide variety of data types, including strings, integer literals and float literals

Integers

Example

x = int(1)   # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3

Floats

Example

x = float(1)     # x will be 1.0
y = float(2.8)   # y will be 2.8
z = float("3")   # z will be 3.0
w = float("4.2") # w will be 4.2

Strings

Example

x = str("s1") # x will be 's1'
y = str(2)    # y will be '2'
z = str(3.0)  # z will be '3.0'

Type Conversion Examples

Converting to Integer

# From float to int
num_float = 9.8
num_int = int(num_float)
print(num_int)  # Output: 9

# From string to int
str_num = "123"
num_int = int(str_num)
print(num_int)  # Output: 123

# From boolean to int
bool_val = True
num_int = int(bool_val)
print(num_int)  # Output: 1

Converting to Float

# From int to float
num_int = 10
num_float = float(num_int)
print(num_float)  # Output: 10.0

# From string to float
str_num = "3.14"
num_float = float(str_num)
print(num_float)  # Output: 3.14

# From boolean to float
bool_val = False
num_float = float(bool_val)
print(num_float)  # Output: 0.0

Converting to String

# From int to string
num_int = 42
str_num = str(num_int)
print(str_num)  # Output: '42'

# From float to string
num_float = 3.14159
str_num = str(num_float)
print(str_num)  # Output: '3.14159'

# From list to string
my_list = [1, 2, 3]
str_list = str(my_list)
print(str_list)  # Output: '[1, 2, 3]'

Common Casting Errors

Be careful when casting, as some conversions may raise errors:

Invalid String to Integer

# This will raise a ValueError
x = int("hello")  # ValueError: invalid literal for int()

Invalid String to Float

# This will raise a ValueError
y = float("abc")  # ValueError: could not convert string to float

Safe Casting with Error Handling

def safe_int_cast(value):
    try:
        return int(value)
    except ValueError:
        print(f"Cannot convert '{value}' to integer")
        return None

# Usage
result = safe_int_cast("123")    # Returns 123
result = safe_int_cast("hello")  # Prints error message, returns None

Advanced Casting

Boolean Casting

# Converting to boolean
print(bool(1))      # True
print(bool(0))      # False
print(bool(""))     # False
print(bool("text")) # True
print(bool([]))     # False
print(bool([1, 2])) # True

List and Tuple Casting

# Converting between list and tuple
my_list = [1, 2, 3, 4]
my_tuple = tuple(my_list)
print(my_tuple)  # (1, 2, 3, 4)

my_tuple = (5, 6, 7, 8)
my_list = list(my_tuple)
print(my_list)   # [5, 6, 7, 8]

# Converting string to list
text = "hello"
char_list = list(text)
print(char_list)  # ['h', 'e', 'l', 'l', 'o']

Casting Can Fail — Handle It

Converting text that is not a valid number raises ValueError. Guard user input with try/except or a validation check.

int("abc")        # ValueError: invalid literal for int() with base 10

raw = "42x"
try:
    n = int(raw)
except ValueError:
    print(f"'{raw}' is not a whole number")

# check first
print("42".isdigit())   # True
print("4.2".isdigit())  # False

Watch Out For These Conversions

ExpressionResultWhy
int(3.9)3Truncates toward zero (no rounding)
int("3.9")ValueErrorNot a valid int string
float("3.9")3.9Valid float string
bool(0), bool("")False"Falsy" values
bool("False")TrueAny non-empty string is truthy!

int(3.9) gives 3, not 4 — it truncates. Use round(3.9) to round to the nearest integer.

Try It Yourself

Exercise 1: Convert the string "3.5" to a number and add 1 to it.

Show solution
print(float("3.5") + 1)   # 4.5

Exercise 2: Safely read an integer, printing an error if the input is not numeric.

Show solution
text = "12ab"
try:
    print(int(text))
except ValueError:
    print("Please enter a whole number.")

Key Takeaways

  • Cast with int(), float(), str(), bool().
  • int() truncates floats; use round() to round.
  • Invalid conversions raise ValueError — wrap risky casts in try/except.
  • Any non-empty string is truthy, so bool("False") is True.

📘 Real-World Deep Dive

User input, network payloads, and database results are always strings until you convert them. Correct casting prevents half the "off-by-one" / "TypeError" bugs in any non-trivial script.

Real-Life Scenario

A CLI that accepts a duration like <code>"2h 35m"</code> and turns it into a number of seconds for scheduling.

Real-Life Example

import re
from datetime import timedelta

DURATION_RX = re.compile(
    r"(?P<hours>\d+)h\s*"
    r"(?:(?P<minutes>\d+)m)?\s*"
    r"(?:(?P<seconds>\d+)s)?",
    re.IGNORECASE,
)

def parse_duration(s: str) -> int:
    m = DURATION_RX.fullmatch(s.strip())
    if not m:
        raise ValueError(f"unparseable duration: {s!r}")
    h = int(m["hours"] or 0)
    mi = int(m["minutes"] or 0)
    se = int(m["seconds"] or 0)
    return int(timedelta(hours=h, minutes=mi, seconds=se).total_seconds())

for raw in ["1h", "2h 35m", "45s", "0H 0M 30S", "bogus"]:
    try:
        print(f"{raw!r:>14} -> {parse_duration(raw)}s")
    except ValueError as e:
        print(f"{raw!r:>14} -> ERROR: {e}")

Expected Output

        '1h' -> 3600s
   '2h 35m' -> 9300s
       '45s' -> 45s
 '0H 0M 30S' -> 30s
      'bogus' -> ERROR: unparseable duration: 'bogus'

Common mistakes

  • int("3.14") raises ValueError — call float(...) first, or use Decimal.
  • bool("False") is True because the string is non-empty; cast via str(x).lower() == "true" instead.
  • list(dict) gives you the keys, not the values — use list(d.values()) explicitly.

🚀 Performance & Best Practices

  • Use int(s, base=16) to parse hex without a manual "0x" strip.
  • For large numeric strings, int(...) is fast; Decimal(...) is slow — pick the precision you actually need.
  • Convert once at the system boundary, then keep typed objects throughout the program.

🧪 Try It Yourself

  1. Extend parse_duration to accept days (3d) and weeks (1w).
  2. Write a parse_date companion that uses datetime.fromisoformat with int() on the year/month/day.
  3. Catch ValueError in parse_duration and return None instead of raising.

FAQ: Python Casting

Common questions about this page.

What is Python Casting?

Python Casting is a Python Tutorial lesson that explains python type casting in Python. Learn how to convert between different data types in Python using casting. Copy the samples and run them in the Python editor. It is written for beginners who want a clear definition and working examples.

Should I run python type casting examples locally for better learning?

Yes. Use the browser editor on StudyGrid for a quick check, then Download the example and run it on your computer. Local runs show real errors and the real toolchain, which is one of the fastest ways to learn python type casting in this Python Tutorial Python lesson (Python Casting).

How do I use python type casting in Python?

To use python type casting in Python, follow the examples on this StudyGrid page. Copy a snippet, run it in the browser, then Download and run it locally for better learning. Change the values and compare the output.

What is the syntax of python type casting?

This Python Casting tutorial shows python type casting syntax with short Python examples. Use the code blocks in this lesson for the exact statements, then try them in your editor.

Python Casting example for beginners

Yes. This page includes a beginner python type casting example you can copy and run. It is designed for searches such as "python type casting for beginners", "python type casting example", and "how to use python type casting".

What are common mistakes with python type casting?

Common python type casting mistakes include wrong syntax, mixing types, and skipping practice. Work through this Python Tutorial chapter in order, run every example, and check the output before moving on.

Why should I learn python type casting?

Python Casting is used in real Python work. Learning python type casting helps you write clearer programs and continue the Python Tutorial tutorial on StudyGrid.

Is Python Casting free to learn online?

Yes. You can learn python type casting free on StudyGrid (studygrid.in). This chapter is part of the Python Tutorial path and includes examples, syntax, and next-step links.