How to change a data type in Python

Learn how to change data types in Python. This guide covers methods, tips, real-world uses, and how to debug common errors.

How to change a data type in Python
Published on: 
Tue
Feb 24, 2026
Updated on: 
Mon
Apr 6, 2026
The Replit Team

In Python, you often need to convert data from one type to another. This process, called type conversion, uses functions like int() and str() for data manipulation and compatibility.

Here, you'll explore techniques to change data types, from basic functions to advanced methods. You will find practical tips, real-world applications, and debugging advice to handle conversions confidently.

Using built-in conversion functions

number_str = "42"
number_int = int(number_str)
number_float = float(number_str)
print(f"String: {number_str}, Integer: {number_int}, Float: {number_float}")--OUTPUT--String: 42, Integer: 42, Float: 42.0

Python’s built-in functions offer a direct path for type conversion. The example shows how a string like "42", which might come from user input or an API call, is converted into numeric types. This step is essential because you can't perform mathematical operations on a string.

The conversion process is explicit and predictable:

  • int() parses the string to create an integer.
  • float() produces a floating-point number.

By converting the string first, you can use the resulting number in calculations without triggering a TypeError.

Common numeric type conversions

Building on these functions, you can also convert between different numeric types, restructure entire sequences, and use comprehensions for more complex transformations.

Converting between numeric types with int(), float(), and complex()

integer_value = 42
float_value = float(integer_value)
complex_value = complex(integer_value)
print(f"Integer: {integer_value}")
print(f"Float: {float_value}")
print(f"Complex: {complex_value}")--OUTPUT--Integer: 42
Float: 42.0
Complex: (42+0j)

Beyond strings, you can also convert between different numeric types. This is often necessary when a calculation requires a specific format, like decimal precision. The process is straightforward and predictable.

  • The float() function converts an integer like 42 into a floating-point number, resulting in 42.0.
  • Using complex() turns the integer into a complex number, where it becomes the real part and the imaginary part defaults to zero, giving you (42+0j).

Converting sequences with list(), tuple(), and set()

my_string = "hello"
my_list = list(my_string)
my_tuple = tuple(my_string)
my_set = set(my_string)
print(f"List: {my_list}\nTuple: {my_tuple}\nSet: {my_set}")--OUTPUT--List: ['h', 'e', 'l', 'l', 'o']
Tuple: ('h', 'e', 'l', 'l', 'o')
Set: {'e', 'h', 'l', 'o'}

You can easily restructure data by converting one sequence type to another. Functions like list(), tuple(), and set() take an iterable—like the string "hello"—and create a new collection from its elements. This process is also known as casting in Python.

  • list() and tuple() both create an ordered sequence of characters from the string.
  • set() is different. It only keeps unique elements, which is why the duplicate 'l' is gone. Notice that sets also don't guarantee the original order.

Converting with comprehensions

numbers = [1, 2, 3, 4, 5]
strings = [str(num) for num in numbers]
squares = {num: num**2 for num in numbers}
print(f"String list: {strings}")
print(f"Square dictionary: {squares}")--OUTPUT--String list: ['1', '2', '3', '4', '5']
Square dictionary: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Comprehensions offer a compact and readable way to create new collections while transforming their elements. They let you combine a loop and a conversion into a single expression, making your code more efficient.

  • The list comprehension applies the str() function to each number, building a new list of strings in one line.
  • Similarly, the dictionary comprehension creates key-value pairs, mapping each number to its square with num: num**2.

This approach is powerful for creating new data structures from existing ones with custom logic.

Advanced type conversion techniques

While direct conversions work for simple types, you'll need more advanced methods to safely parse complex data and gracefully handle potential conversion failures.

Using ast.literal_eval() for safe string to container conversion

import ast
list_string = "[1, 2, 3, 4]"
dict_string = "{'a': 1, 'b': 2}"
parsed_list = ast.literal_eval(list_string)
parsed_dict = ast.literal_eval(dict_string)
print(f"Parsed list: {parsed_list}, type: {type(parsed_list)}")
print(f"Parsed dict: {parsed_dict}, type: {type(parsed_dict)}")--OUTPUT--Parsed list: [1, 2, 3, 4], type: <class 'list'>
Parsed dict: {'a': 1, 'b': 2}, type: <class 'dict'>

When you receive data as a string that represents a Python container, like "[1, 2, 3, 4]", you can't use it as a list directly. The ast.literal_eval() function is the perfect tool for this job. It safely parses the string and converts it back into its original data structure in a memory-efficient way.

  • It's much safer than the general eval() function because it only processes literals—strings, numbers, lists, and dictionaries.
  • It won't execute complex expressions or functions, preventing potential security risks from malicious strings.

Handling conversion errors with try/except

def safe_convert(value, target_type):
try:
return target_type(value), True
except (ValueError, TypeError):
return None, False

results = [safe_convert("42", int), safe_convert("hello", int), safe_convert(3.14, int)]
for result, success in results:
print(f"Result: {result}, Success: {success}")--OUTPUT--Result: 42, Success: True
Result: None, Success: False
Result: 3, Success: True

Not all conversions succeed. Attempting to turn a non-numeric string like "hello" into an integer raises a ValueError, which can crash your program. Wrapping the conversion in a try/except block provides a safety net to handle these failures gracefully, using proper try and except in Python techniques, similar to how code repair automatically fixes errors in your programs.

The safe_convert function demonstrates this by attempting a conversion and returning a tuple indicating success or failure.

  • The try block runs the conversion. If it works, it returns the result and True.
  • If a ValueError or TypeError occurs, the except block catches it, preventing a crash and returning None and False.

Creating custom type conversions with class methods

class DataConverter:
@staticmethod
def to_bool(value):
if isinstance(value, str):
return value.lower() in ('yes', 'true', '1', 'y', 't')
return bool(value)

test_values = ["yes", "no", 1, 0, "True", "False"]
for value in test_values:
print(f"{value} → {DataConverter.to_bool(value)}")--OUTPUT--yes → True
no → False
1 → True
0 → False
True → True
False → False

Sometimes, Python's default conversions don't quite fit your needs. You can create your own specific conversion rules by defining methods within a class, similar to how vibe coding lets you build custom logic with natural language. The DataConverter class uses a @staticmethod, which lets you call the to_bool method directly without creating a class instance.

  • This custom function intelligently handles various string inputs, recognizing values like 'yes' and 'true' as boolean True.
  • For any other data type, it simply uses Python's standard bool() conversion, providing a reliable fallback.

Move faster with Replit

Replit is an AI-powered development platform that comes with all Python dependencies pre-installed, so you can skip setup and start coding instantly. This lets you move from learning individual techniques, like the conversion methods in this article, to building complete applications.

Instead of piecing together functions, you can describe the app you want to build, and Agent 4 will take it from an idea to a working product. It handles writing the code, connecting to databases, and even deployment.

  • A user input validator that uses a try/except block to safely convert web form data into integers or floats.
  • A configuration parser that uses custom methods to interpret string values like 'true' or 'yes' as proper booleans.
  • An API data processor that uses ast.literal_eval() to turn string-formatted lists and dictionaries into native Python objects.

Simply describe your app, and Replit will write the code, test it, and fix issues automatically, all within your browser.

Common errors and challenges

Even with the right tools, type conversion can lead to tricky errors like unexpected data loss or program crashes if you’re not careful.

Debugging ValueError when converting strings to numbers

A ValueError is one of the most common roadblocks, especially when converting strings to numbers. It happens when a value is the correct type but isn't in the right format for the conversion, like trying to run int("hello"). This often occurs with user input or data fetched from an external file that contains non-numeric characters.

While a try/except block is great for handling this error, you can also prevent it by validating the string first. You can use string methods like .isdigit() to check if a string contains only numbers before you even attempt the conversion.

Avoiding data loss when converting between collection types

Converting between collection types like lists, tuples, and sets is powerful, but it can cause silent data loss. The most frequent issue arises when converting a list or tuple to a set, as sets only store unique elements. Any duplicates in your original sequence will be permanently discarded.

  • For example, converting the list ['apple', 'banana', 'apple'] to a set results in {'apple', 'banana'}.
  • You also lose the original order of the elements because sets are inherently unordered. When you convert it back to a list, there's no guarantee the new list will match the original sequence.

Handling TypeError when converting complex or nested types

A TypeError occurs when you try to perform an operation on an unsupported data type. For instance, you can't pass a whole list to the int() function, so code like int([1, 2]) will fail. This error often appears when working with nested data structures, where you might accidentally try to convert a container instead of the elements inside it.

To avoid this, you need to access the individual elements before converting them. You can iterate through the collection with a loop or use a comprehension. It's also good practice to check a variable's type with the isinstance() function to ensure it's compatible before you attempt a conversion.

Debugging ValueError when converting strings to numbers

A ValueError is a common hurdle when converting strings to numbers. It happens when a string contains non-numeric characters, which prevents functions like int() from parsing it. See what happens when the code below tries to convert an invalid string.

user_input = "42abc"
number = int(user_input) # This will raise ValueError
print(f"Converted number: {number}")

The int() function fails because it can't parse the string '42abc'. It expects a string containing only digits, and the trailing letters trigger the error. The code below shows how to handle this safely.

user_input = "42abc"
if user_input.isdigit():
number = int(user_input)
print(f"Converted number: {number}")
else:
print(f"Invalid input: {user_input} contains non-digit characters")

This solution prevents the error by validating the string before attempting the conversion. Instead of reacting to a crash, you can proactively check the input.

  • The .isdigit() method confirms the string contains only numeric characters before int() is called.

This is crucial when working with data from external sources, like user input or API responses, where the format isn't guaranteed.

Avoiding data loss when converting between collection types

Converting between collection types can lead to silent data loss, and it's not just about losing duplicates. When you convert a dictionary to a list, for example, you might be surprised by what gets left behind. See what happens below.

user_data = {"name": "Alice", "age": 30, "active": True}
converted_data = list(user_data)
print(f"Converted data: {converted_data}")

The list() function only grabs the dictionary's keys, leaving the values behind. This is a common source of silent data loss. See how to target specific parts of the dictionary for conversion in the following example.

user_data = {"name": "Alice", "age": 30, "active": True}
converted_data = list(user_data.items())
print(f"Converted data: {converted_data}")

To preserve both keys and values, you'll need to explicitly target them. By calling the .items() method on the dictionary, you convert its key-value pairs into a list of tuples.

  • This approach ensures you don't accidentally discard the dictionary's values.

The resulting list, such as [('name', 'Alice'), ('age', 30)], keeps all the original data intact. Keep this in mind whenever you need to restructure dictionary data without losing information.

Handling TypeError when converting complex or nested types

You'll also get a TypeError for logically impossible conversions, like trying to use int() on a complex number. Python won't guess how to handle the imaginary part, so it stops with an error. See what happens in the code below.

complex_object = complex(3, 4)
int_value = int(complex_object) # This will raise TypeError
print(f"Converted value: {int_value}")

The int() function fails because it has no default way to handle the imaginary component of a complex number. You must explicitly choose which part to convert. The code below demonstrates the correct approach.

complex_object = complex(3, 4)
int_value = int(complex_object.real)
print(f"Real part converted to int: {int_value}")

Python raises a TypeError because it doesn't know how to convert a complex number with both real and imaginary parts into a single integer. You must be explicit about which part you want to convert.

  • To fix this, you can access the number's real part using .real before passing it to the int() function.

This ensures the conversion is unambiguous, preventing the error when working with multi-component numeric types.

Real-world applications

Understanding how to manage conversion errors is key to working with real-world data from sources like CSV files and JSON API responses.

Processing CSV data with float() and int() for analytics

Processing data from a CSV file for tasks like calculating sales requires converting text-based numbers into usable float() and int() values.

sales_data = ["product,price,quantity", "Laptop,999.99,5", "Keyboard,45.50,12", "Mouse,22.99,30"]

total_sales = 0
for line in sales_data[1:]:
name, price, quantity = line.split(',')
item_total = float(price) * int(quantity)
total_sales += item_total
print(f"{name}: ${item_total:.2f}")

print(f"Total sales: ${total_sales:.2f}")

This code simulates processing raw data, like from a file. For real-world applications, you'd start by reading a CSV file in Python before unpacking each comma-separated string into variables for product, price, and quantity.

  • The key step is converting text to numbers. The price string becomes a decimal with float(), and the quantity string becomes a whole number with int().
  • This conversion is necessary because you can't perform math on strings. Multiplying the original text would raise a TypeError.

By converting first, the code can correctly calculate and aggregate the total sales.

Converting JSON API responses with json.loads() and type conversion

When processing a JSON API response, you'll use the json.loads() function to parse the data string, then explicitly convert values like "42" or "true" into usable integers and booleans.

import json

api_response = '''{"user": {"id": "1001", "name": "Alice Smith",
"active": "true", "login_count": "42",
"settings": {"theme": "dark", "notifications": "off"}}}'''

data = json.loads(api_response)
user = data["user"]

user_id = int(user["id"])
is_active = user["active"].lower() == "true"
login_count = int(user["login_count"])

print(f"User {user['name']} (ID: {user_id})")
print(f"Active: {is_active}, Logins: {login_count}")
print(f"Theme: {user['settings']['theme']}")

This code demonstrates the necessary post-processing after parsing a JSON string. The json.loads() function converts the string into a Python dictionary, but it doesn't automatically infer the correct data types for values that are also formatted as strings, like "1001" or "true".

  • You must explicitly convert numeric strings to integers using the int() function.
  • For booleans, a robust approach is to use a string comparison, such as .lower() == "true", to correctly interpret the value.

These extra steps ensure the data is in a usable format for your application. This type conversion process is especially important when converting JSON to CSV in Python.

Get started with Replit

Turn these techniques into a real tool. Tell Replit Agent to "build a unit converter that safely handles float inputs" or "create a script that cleans CSV data by converting string numbers."

The Agent writes the code, tests for errors, and deploys the app directly from your prompt. Start building with Replit.

Build your first app today

Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.

Build your first app today

Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.