Skip to content

Understanding Data Type Conversion (Type Casting) in Python

Updated: at 01:50 AM

Data types are an important concept in Python and all programming languages. They allow you to store different types of data in variables, such as integers, floating-point numbers, strings, booleans, etc. Each data type has its own properties and supported operations.

Sometimes, you may need to convert a value from one data type to another in order to perform certain operations or to meet the requirements of a function’s parameters. This conversion between data types is known as type casting or type conversion.

In this comprehensive guide, we will cover the following topics related to understanding data type conversion in Python:

Table of Contents

Open Table of Contents

Overview of Built-in Data Types in Python

Python contains the following built-in data types:

Here is a quick overview of some of the commonly used data types in Python:

Each data type has different properties and supports different operations. For example, numeric types like ints and floats can be used in math operations, while strings have methods for text manipulation.

Now let’s look at how we can convert between these data types in Python.

Type Conversion Functions in Python

Python provides a few built-in functions and methods to easily convert between data types:

Some types also have specific conversion methods:

Here are some examples of using these type conversion functions in Python:

num_int = 5
num_float = float(num_int) # 5.0

num_str = '456'
num_int = int(num_str) # 456

pi_float = 3.14
pi_str = str(pi_float) # "3.14"

is_true = bool(1) # True

These functions provide a straightforward way to convert between core data types in Python.

Implicit vs Explicit Type Conversions

In Python, type conversions can occur implicitly (automatically) or explicitly (manually).

Implicit type conversion happens when Python automatically converts one data type to another without any function call. This usually occurs when you perform operations with incompatible data types.

For example:

num_int = 100
num_float = 1.23

result = num_int + num_float # 101.23 (float)

Here Python automatically converted the integer to a float to perform the addition operation.

Explicit type conversion occurs when you manually convert between types by calling the type conversion functions.

For example:

num_int = 100
num_str = "1.23"

num_float = float(num_str) # 1.23
result = num_int + num_float # 101.23

Here we explicitly converted the string to a float using float() before doing the addition.

In general, explicit conversions are recommended because they make your intentions clear. Implicit conversions can cause unexpected results if you are not careful.

Now let’s look at some useful type casting operations between common data types in Python.

Type Casting Between Common Data Types

Here are some practical examples of converting between the core data types of strings, integers, floats, booleans, and more in Python.

Strings to Integers/Floats

To convert a string to an integer, use int() and pass the string value:

num_str = "456"
num_int = int(num_str) # 456

For floats, use float():

num_str = "45.6"
num_float = float(num_str) # 45.6

The string must contain a valid integer or float value, otherwise you will get a ValueError:

num_str = "hello"
int(num_str) # ValueError: invalid literal for int()

Integers to Floats

Use float() to convert an integer to a float:

num_int = 100
num_float = float(num_int) # 100.0

Floats to Integers

To convert a float to an integer, you can use int(), but note this will truncate the fractional part:

num_float = 1.23
num_int = int(num_float) # 1

To round to the nearest integer, use the round() function before converting to int:

num_float = 1.75
num_int = int(round(num_float)) # 2

Booleans to Integers/Strings

Boolean values True and False can convert to 1 and 0 for integers:

is_true = True
num = int(is_true) # 1

is_false = False
num = int(is_false) # 0

For strings, True becomes “True” and False becomes “False”:

is_true = True
str(is_true) # "True"

is_false = False
str(is_false) # "False"

Integers/Floats to Strings

To convert integers or floats to strings, use the str() function:

num_int = 100
num_str = str(num_int) # "100"

num_float = 1.23
num_str = str(num_float) # "1.23"

This will convert the number into its string representation.

Best Practices for Type Conversions

Here are some best practices to follow for type conversions in Python:

Handling Errors During Type Casting

Type casting can potentially fail and raise exceptions if the conversion cannot be performed. Here is how to handle errors gracefully using try/except blocks:

try:
    num = int("abc")
except ValueError:
    print("Cannot convert string to integer")

try:
    num = float("1/0")
except ValueError:
    print("Cannot convert invalid string to float")

Some common exceptions encountered during type casting:

The best way to handle these exceptions is to:

  1. Use try/except blocks to anticipate potential errors.

  2. Print custom error messages so its clear to the user what went wrong.

  3. Optionally, use a fallback value or retry with different input.

Robust type conversion handling is important to build reliable programs that don’t crash unexpectedly.

Type Conversion Use Cases and Examples

Some practical examples of where type conversions are useful in Python:

Let’s look at some code examples:

User Input:

age_input = input("Enter your age: ")
age = int(age_input) # Convert to int

Reading CSV Files:

import csv

with open("data.csv") as f:
  reader = csv.reader(f)
  for row in reader:
    number = float(row[0]) # Convert strings to floats
    name = str(row[1]) # Convert to string

Format Strings:

value = 128.75
print(f"The value is: {str(value)}") # Convert float to string

Calling Functions:

def calculate_sum(x, y):
   return x + y

# Pass string numbers
sum = calculate_sum("4", "5") # Covert to ints

These examples demonstrate how type conversions allow you to work with varied data in Python programs.

Conclusion

In summary, type conversion or type casting is an important concept that allows flexibility when working with different data types in Python. The key takeaways are:

With this comprehensive guide, you should have a strong grasp on type conversions in Python. The ability to properly convert data types is essential knowledge for any Python programmer.