Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Data Type Conversion in Python
Data type conversion in Python allows you to transform one data type into another. Python provides built-in functions to perform these conversions, which return new objects representing the converted values.
Common Type Conversion Functions
| Function | Description | Example |
|---|---|---|
int() |
Converts to integer |
int("42") ? 42
|
float() |
Converts to floating-point |
float("3.14") ? 3.14
|
str() |
Converts to string |
str(42) ? "42"
|
bool() |
Converts to boolean |
bool(1) ? True
|
list() |
Converts to list |
list("abc") ? ['a', 'b', 'c']
|
tuple() |
Converts to tuple |
tuple([1, 2, 3]) ? (1, 2, 3)
|
Converting to Numeric Types
String to Integer
Convert string numbers to integers using int() ?
# String to integer conversion
number_str = "42"
number_int = int(number_str)
print(f"String: {number_str}, Type: {type(number_str)}")
print(f"Integer: {number_int}, Type: {type(number_int)}")
# With different bases
binary_str = "1010"
decimal_from_binary = int(binary_str, 2)
print(f"Binary '1010' to decimal: {decimal_from_binary}")
String: 42, Type: <class 'str'> Integer: 42, Type: <class 'int'> Binary '1010' to decimal: 10
String to Float
Convert strings to floating-point numbers ?
# String to float conversion
price_str = "19.99"
price_float = float(price_str)
print(f"String: {price_str}, Type: {type(price_str)}")
print(f"Float: {price_float}, Type: {type(price_float)}")
# Scientific notation
scientific = "1.5e3"
result = float(scientific)
print(f"Scientific notation: {scientific} = {result}")
String: 19.99, Type: <class 'str'> Float: 19.99, Type: <class 'float'> Scientific notation: 1.5e3 = 1500.0
Converting to String Type
Use str() to convert any object to its string representation ?
# Various types to string
number = 42
pi = 3.14159
is_active = True
data = [1, 2, 3]
print(f"Integer to string: {str(number)}")
print(f"Float to string: {str(pi)}")
print(f"Boolean to string: {str(is_active)}")
print(f"List to string: {str(data)}")
Integer to string: 42 Float to string: 3.14159 Boolean to string: True List to string: [1, 2, 3]
Converting Between Collection Types
Convert between lists, tuples, and sets ?
# Original list
numbers = [1, 2, 3, 2, 4]
# Convert to different types
numbers_tuple = tuple(numbers)
numbers_set = set(numbers) # Removes duplicates
numbers_back_to_list = list(numbers_set)
print(f"Original list: {numbers}")
print(f"To tuple: {numbers_tuple}")
print(f"To set: {numbers_set}")
print(f"Back to list: {numbers_back_to_list}")
Original list: [1, 2, 3, 2, 4]
To tuple: (1, 2, 3, 2, 4)
To set: {1, 2, 3, 4}
Back to list: [1, 2, 3, 4]
Character and ASCII Conversions
Convert between characters and their ASCII values ?
# Character to ASCII and back
char = 'A'
ascii_value = ord(char)
back_to_char = chr(ascii_value)
print(f"Character: {char}")
print(f"ASCII value: {ascii_value}")
print(f"Back to character: {back_to_char}")
# Convert number to hex and octal
number = 255
hex_value = hex(number)
oct_value = oct(number)
print(f"Number: {number}")
print(f"Hexadecimal: {hex_value}")
print(f"Octal: {oct_value}")
Character: A ASCII value: 65 Back to character: A Number: 255 Hexadecimal: 0xff Octal: 0o377
Boolean Conversion
Python follows specific rules for boolean conversion ?
# Different values to boolean
values = [0, 1, "", "hello", [], [1, 2], None]
for value in values:
boolean_result = bool(value)
print(f"{repr(value):10} ? {boolean_result}")
0 ? False 1 ? True '' ? False 'hello' ? True [] ? False [1, 2] ? True None ? False
Handling Conversion Errors
Some conversions may fail and raise exceptions ?
# Safe conversion with error handling
def safe_int_convert(value):
try:
return int(value)
except ValueError:
return f"Cannot convert '{value}' to integer"
test_values = ["42", "3.14", "hello", ""]
for value in test_values:
result = safe_int_convert(value)
print(f"Converting '{value}': {result}")
Converting '42': 42 Converting '3.14': Cannot convert '3.14' to integer Converting 'hello': Cannot convert 'hello' to integer Converting '': Cannot convert '' to integer
Conclusion
Python's built-in type conversion functions make it easy to transform data between different types. Always handle potential conversion errors when working with user input or uncertain data sources.
