Type Casting
Learn Python type casting (conversion) for data science & AI. Understand implicit and explicit casting to convert strings to numbers, crucial for LLM and machine learning data processing.
1.4 Type Casting in Python
Type casting, also known as type conversion, is the process of converting a variable or value from one data type to another in Python. This is a fundamental operation that allows you to transform data, for instance, converting a string representation of a number into an integer or a float, which is crucial when processing user input or data from external sources.
Python offers two primary types of type casting:
Implicit Type Casting (Automatic Conversion)
Explicit Type Casting (Manual Conversion)
Implicit Type Casting (Automatic Conversion)
Implicit type casting occurs automatically when Python converts one data type to another during the evaluation of an expression, without requiring explicit intervention from the programmer. This typically happens when there's a potential for data loss if the conversion were not performed.
Python is a strongly typed language, meaning it generally does not allow automatic conversion between unrelated data types (like strings and numbers). However, it handles safe conversions between compatible numeric types seamlessly. For example, during arithmetic operations involving integers and floats, the integer is automatically promoted to a float to avoid losing precision.
Example:
num1 = 12 # Integer
num2 = 3.7 # Float
result = num1 + num2
print(result)
Output:
15.7
In this example, num1
(an integer) is implicitly cast to a float (12.0
) before the addition with num2
(a float). This ensures that the operation is performed with floating-point precision, and the final result is a float.
How Python Handles Implicit Casting (Type Promotion)
Python follows a type promotion hierarchy to avoid data loss during implicit conversions. Generally, a smaller or less precise data type is promoted to a larger or more precise one. The typical promotion order is:
bool
→ int
→ float
→ complex
Example with Booleans:
flag = True # Equivalent to 1
value = 7.5 # Float
total = flag + value
print(total)
Output:
8.5
Explanation: In this case, True
is treated numerically as 1
. Since 1
(an integer) is a smaller data type than 7.5
(a float), Python implicitly converts 1
to 1.0
before the addition, resulting in 8.5
.
Explicit Type Casting (Manual Conversion)
Explicit type casting involves manually converting a value from one data type to another using Python's built-in conversion functions. This is necessary when automatic conversion is not possible or safe, such as converting a string containing numeric characters into an integer or float.
The primary built-in functions for explicit type casting are:
int()
float()
str()
The int()
Function – Convert to Integer
The int()
function can convert various data types to integers. It behaves as follows:
Integers: If the input is already an integer, it remains unchanged.
Floats: It truncates the decimal part of a float, effectively removing everything after the decimal point.
Strings: It converts a string to an integer, provided the string contains a valid whole number representation.
Booleans:
True
is converted to1
, andFalse
is converted to0
.
Valid Conversions:
a = int(25.9) # Float to int (truncates)
b = int("42") # String to int
c = int(True) # Boolean to int
print(a, b, c)
Output:
25 42 1
Invalid Conversions (Raising ValueError
):
## x = int("12.7") # Error: String with decimal part is not a valid integer
## y = int("hello123") # Error: String is not numeric
These attempts would raise a ValueError
because the input strings do not represent pure whole numbers.
Converting from Binary, Octal, or Hexadecimal Strings
The int()
function can also convert strings representing numbers in different bases (binary, octal, hexadecimal) by specifying the base
argument:
binary_str = int("1101", 2) # Binary to Decimal
octal_str = int("17", 8) # Octal to Decimal
hex_str = int("1F", 16) # Hexadecimal to Decimal
print(binary_str, octal_str, hex_str)
Output:
13 15 31
The float()
Function – Convert to Float
The float()
function converts various data types into floating-point numbers:
Integers: Converts an integer to a float by appending
.0
.Strings: Converts a string to a float, provided the string contains a valid number (integer or float). It also accepts strings in scientific notation.
Examples:
a = float(3) # Integer to float
b = float("5.67") # String to float
c = float("1e3") # Scientific notation to float (1.5 * 10^3)
print(a, b, c)
Output:
3.0 5.67 1000.0
Invalid Conversion (Raising ValueError
):
## d = float("2,000.55") # Invalid due to comma
This raises a ValueError
because float()
does not recognize formatted numbers with commas.
Example: Converting Various Types Explicitly
a = int(3.8) # Float to int (truncates to 3)
b = float(7) # Integer to float (converts to 7.0)
c = int("20") # String to int
d = float("8.9") # String to float
e = int(True) # Boolean to int (converts to 1)
print(a, b, c, d, e)
Output:
3 7.0 20 8.9 1
The str()
Function – Convert to String
The str()
function converts almost any Python object into its string representation. This is invaluable for displaying information, concatenating strings, or preparing data for storage or output.
Syntax:
str(object, encoding=encoding, errors=errors)
object
(required): The value or object to convert.encoding
(optional): Used for converting bytes to strings.errors
(optional): How to handle encoding/decoding errors.
For most common use cases, only the object
argument is needed.
Examples:
## Converting Integers to Strings
num = 45
text = str(num)
print(text)
print(type(text))
## Converting Floats to Strings
price = 129.99
text_price = str(price)
print(text_price)
print(type(text_price))
## Handling Scientific Notation
sci_num = str(1.5e3) # 1.5 * 10^3
print(sci_num)
## Converting Booleans and Other Objects
print(str(True))
print(str(False))
print(str([1, 2, 3])) # List
print(str((4, 5, 6))) # Tuple
print(str({'x': 10})) # Dictionary
## Converting Expressions
text_expr = str(3 * 5)
print(text_expr)
Output:
45
<class 'str'>
129.99
<class 'str'>
1500.0
True
False
[1, 2, 3]
(4, 5, 6)
{'x': 10}
15
Practical Example:
a = str(5) # Integer to String
b = str(6.3) # Float to String
c = str("7.1") # Already a String (remains the same)
print(a, b, c)
Output:
5 6.3 7.1
Conversion Between Sequence Types
Python provides functions to convert between different sequence types like strings, lists, and tuples.
String to List: The
list()
function breaks a string into a list of individual characters.word = "Python" char_list = list(word) print(char_list)
Output:
['P', 'y', 't', 'h', 'o', 'n']
List to Tuple: The
tuple()
function converts a list into a tuple.nums = [1, 2, 3] as_tuple = tuple(nums) print(as_tuple)
Output:
(1, 2, 3)
Tuple to List: The
list()
function converts a tuple into a list.data = (4, 5, 6) as_list = list(data) print(as_list)
Output:
[4, 5, 6]
List/Tuple to String: Using
str()
on a list or tuple returns a string representation of the entire sequence, including its brackets or parentheses. For joining elements into a single string, thestr.join()
method is more appropriate.lst = [10, 20] tpl = (30, 40) print(str(lst)) print(str(tpl))
Output:
[10, 20] (30, 40)
Revision Table – Key Conversion Functions
| Function | Converts From | Converts To | Notes | | :------------ | :----------------------------------------------- | :------------ | :---------------------------------------------------------------------------------- | | int(x)
| Float, String, Bool, (Bin/Oct/Hex String) | Integer | Truncates decimal part of floats. Raises ValueError
for invalid string formats. | | float(x)
| Int, String, Scientific Notation String | Float | Appends .0
to integers. Accepts valid numeric strings and scientific notation. | | str(x)
| Any data type (int, float, bool, list, dict, etc.) | String | Converts to a human-readable string representation. | | repr(x)
| Any data type | String | Returns an "official" string representation, often useful for debugging. | | eval(x)
| String | Python object | Evaluates a string as a Python expression. Use with caution. | | tuple(s)
| Iterable (list, string, etc.) | Tuple | | | list(s)
| Iterable (tuple, string, etc.) | List | | | set(s)
| Iterable | Set | Removes duplicate elements. | | dict(pairs)
| Iterable of key-value pairs | Dictionary | | | chr(i)
| Integer | Unicode Char | Converts an integer Unicode code point to a character. | | ord(c)
| Character | Integer | Converts a character to its integer Unicode code point. | | hex(i)
| Integer | Hex String | Returns hexadecimal representation (e.g., 0x1f
). | | oct(i)
| Integer | Octal String | Returns octal representation (e.g., 0o17
). |
Note: In Python 3, long()
and unichr()
have been removed as int()
and chr()
now handle all integer-to-character and arbitrary-precision integer needs respectively.
Caution Points
Complex Numbers: You cannot directly convert complex numbers using
int()
orfloat()
.String Format: Always ensure that strings are in the correct format for the target data type before attempting conversion. For example,
int("12.7")
orfloat("2,000.55")
will fail.Implicit Casting Limitations: Implicit casting is primarily limited to safe conversions between compatible numeric types.
Final Note on str()
vs. repr()
str()
: Aimed at producing a human-readable and understandable string representation of an object.repr()
: Aimed at producing an unambiguous string representation that, if possible, could be used to re-create the object (e.g.,eval(repr(obj)) == obj
). It's often more useful for debugging purposes.
SEO Keywords
Python type casting, Implicit vs explicit conversion, Python int function, Python float conversion, Python str usage, String to int Python, Data type conversion Python, Python type conversion table, Convert list to tuple Python, Python sequence conversion.
Possible Interview Questions
What is type casting in Python, and why is it important?
Explain the difference between implicit and explicit type casting with examples.
How does Python handle implicit type conversion during arithmetic operations?
What are some common use cases for the
int()
,float()
, andstr()
functions?What will happen if you try to convert a string like
"12.7"
usingint()
? Why?How does Python convert boolean values during numeric operations?
Can you convert strings representing binary, octal, or hexadecimal using
int()
? How?What is the difference between
str()
andrepr()
in Python?How can you convert a list to a tuple and vice versa in Python?
Why does
float("2,000.55")
raise an error, and how can you fix it?