var = 123 var = "CodeOp loves Python." print(var)
Run that code, and you’ll get an output without any error. That’s because Python is a dynamic language. And that’s why I, along with countless other coders across the globe, love this language.
Type conversion, or typecasting, involves changing an object from one data type to another. It can be incredibly important when you need different data types to interact with or meet specific library or API requirements.
Central to Python’s flexibility is its approach to data types and operations involving them. Keep reading, and you’ll realise how easy it is to type conversions in Python 3.
1. Implicit Type Conversion
Implicit type conversion, also known as type coercion, is the automatic conversion of data types by the Python interpreter. This process occurs during runtime, without explicit direction from the programmer.
Numeric Conversion
num_int = 10 # An integer num_float = 5.5 # A float # Adding an integer and a float results in a float result = num_int + num_float print(result) # Output: 15.5 print(type(result)) # Output: <class 'float'>
Boolean and Integer
a = True # Boolean b = 2 # Integer # Boolean True is treated as 1 result = a + b print(result) # Output: 3 print(type(result)) # Output: <class 'int'>
String and Integer in Print Statement
string = "The count is" # String count = 5 # Integer
You can’t directly add an integer with a string because they’re vastly different data types. So, for this, you’ll have to either do explicit conversion or use a formatted string.
print(f"The count is {count}")
Formatted string is denoted by f”write_contents_here {variable_placeholder}”
Limitations of Implicit Conversions
While implicit conversions simplify many operations, they can also lead to subtle bugs and unexpected behaviour
Operations not clearly defined for mixed types without an explicit conversion will raise errors. For example, adding a string and an integer directly results in a TypeError.
2. Explicit Type Conversion
Explicit type conversion, or typecasting, is when the programmer directs the program to convert data from one type to another using built-in Python functions.
Converting to Integers
print(int(3.5)) # Outputs: 3 print(int('10')) # Outputs: 10 print(int(True)) # Outputs: 1
Note: int() cannot directly convert strings with decimal points or non-numeric strings and will raise a value error if attempted.
Converting to Floats
print(float(1)) # Outputs: 1.0 print(float('3.14')) # Outputs: 3.14 print(float('10')) # Outputs: 10.0
Note: Similar to int(), trying to convert a non-numeric string to a float will result in a value error.
Converting to Strings
Here’s how you use the str() function.
print(str(10)) # Outputs: '10' print(str(3.14)) # Outputs: '3.14' print(str([1, 2, 3])) # Outputs: '[1, 2, 3]'
Using str.join():
elements = ['Hello', 'world'] greeting = ' '.join(elements) print(greeting) # Outputs: "Hello world"
If you know how to use list comprehension, you can do it like this:
numbers = [1, 2, 3, 4] strings = [str(num) for num in numbers] result = ', '.join(strings) print(result) # Outputs: "1, 2, 3, 4"
Using map():
It does what it says. The map() method maps the data to the desired data type.
numbers = [1, 2, 3] strings = map(str, numbers) # Converts numbers to strings result = ', '.join(strings) print(result) # Outputs: "1, 2, 3"
Using str.format():
template = "{0} is {1} years old." sentence = template.format("John", 30) Print (sentence) # Outputs: "John is 30 years old."
Converting to Boolean Values
print(bool(1)) # Outputs: True print(bool(0)) # Outputs: False print(bool('')) # Outputs: False print(bool('Hello')) # Outputs: True
Database and API Interactions
Converting complex data structures to JSON format using JSON.dumps() is common when interacting with databases or APIs.
import json data_dict = {'id': 101, 'name': 'John'} json_data = json.dumps(data_dict) # Now, json_data can be sent as a payload to an API
3. Converting Between Collections
Python provides straightforward functions for these conversions:
Convert to List: The list() function converts a given iterable (tuples, sets, dictionaries) into a list.
my_tuple = (1, 2, 3) my_list = list(my_tuple) print(my_list) # Output: [1, 2, 3]
Convert to Tuple: The tuple() function transforms a list or set into a tuple.
my_list = [1, 2, 3] my_tuple = tuple(my_list) print(my_tuple) # Output: (1, 2, 3)
Convert to Set: The set() function turns a list or tuple into a set, automatically removing duplicate elements.
my_list = [1, 1, 2, 3, 3] my_set = set(my_list) print(my_set) # Output: {1, 2, 3}
Converting to Dictionaries: zip() and dict() are commonly used together to create a dictionary from two lists or tuples, where one serves as a key and the other as a value.
keys = ['name', 'age', 'gender'] values = ['John', 30, 'Male'] my_dict = dict(zip(keys, values)) print(my_dict) # Output: {'name': 'John', 'age': 30, 'gender': 'Male'}
4. User Input Handling
User inputs through functions like input() are received as strings. Conversion to integers or floats is necessary to use these inputs in numerical calculations.
age = input("Enter your age: ") age = int(age) # Convert to integer print(f"You are {age} years old.")