Type Conversion Functions

Type Conversion Functions in Python ๐Ÿ”„

Type conversion (or type casting) transforms data from one type to another. Python provides built-in functions for these conversions. Here’s a comprehensive guide with examples:


1. int(x) ๐Ÿ”ข

Converts x to an integer.

Python

print(int(3.14))        # 3 (float โ†’ int)
print(int("42"))        # 42 (str โ†’ int)
print(int(True))        # 1 (bool โ†’ int)
print(int("1010", 2))   # 10 (binary str โ†’ int)
# print(int("Hello"))   # โŒ ValueError (non-numeric string)

2. float(x) afloat

Converts x to a floating-point number.

Python

print(float(42))        # 42.0 (int โ†’ float)
print(float("3.14"))    # 3.14 (str โ†’ float)
print(float(False))     # 0.0 (bool โ†’ float)
# print(float("1a.5"))  # โŒ ValueError (invalid string)

3. str(x) ๐Ÿ’ฌ

Converts x to a string. Works with any data type.

Python

print(str(100))         # '100' (int โ†’ str)
print(str(7.8e-2))      # '0.078' (float โ†’ str)
print(str([1, 2, 3]))   # '[1, 2, 3]' (list โ†’ str)
print(str(True))        # 'True' (bool โ†’ str)

4. bool(x) โœ…โŒ

Converts x to a Boolean (True or False).

Falsy values: 0, 0.0, “”, [], (), {}, None

Truthy values: Everything else.

Python

print(bool(0))          # False (int)
print(bool("Hello"))    # True (non-empty str)
print(bool([]))         # False (empty list)
print(bool(3.14))       # True (non-zero float)

5. list(x) ๐Ÿ“‹

Converts iterable x to a list.

Python

print(list("abc"))      # ['a', 'b', 'c'] (str โ†’ list)
print(list((1, 2, 3)))  # [1, 2, 3] (tuple โ†’ list)
print(list({4, 5, 6}))  # [4, 5, 6] (set โ†’ list; order not guaranteed)
print(list({'a': 1}))   # ['a'] (dict โ†’ list of keys)

6. tuple(x) ๐Ÿ“ฆ

Converts iterable x to a tuple.

Python

print(tuple([1, 2, 3])) # (1, 2, 3) (list โ†’ tuple)
print(tuple("hi"))      # ('h', 'i') (str โ†’ tuple)

7. set(x) ๐Ÿ“š

Converts iterable x to a set (removes duplicates).

Python

print(set([1, 2, 2, 3])) # {1, 2, 3} (list โ†’ set)
print(set("apple"))      # {'a', 'p', 'l', 'e'} (str โ†’ set)

8. dict(x) ๐Ÿ—บ๏ธ

Converts iterable of key-value pairs to a dictionary.

Python

print(dict([('a', 1), ('b', 2)]))  # {'a': 1, 'b': 2} (list of tuples โ†’ dict)
print(dict(a=1, b=2))              # {'a': 1, 'b': 2} (keyword args โ†’ dict)

9. chr(x) & ord(x) ๐Ÿ…ฐ๏ธโžก๏ธ๐Ÿ”ข

  • chr(i): Converts Unicode code point i to a character.
  • ord(c): Converts character c to its Unicode code point.

Python

print(chr(65))          # 'A' (int โ†’ char)
print(ord('A'))         # 65 (char โ†’ int)
print(chr(128512))      # '๐Ÿ˜€' (emoji)

10. bin(x), oct(x), hex(x) ๐Ÿ”ขโžก๏ธ๐Ÿ”ก

Convert integers to string representations in different bases.

Python

print(bin(42))          # '0b101010' (int โ†’ binary str)
print(oct(42))          # '0o52' (int โ†’ octal str)
print(hex(42))          # '0x2a' (int โ†’ hexadecimal str)

Implicit vs. Explicit Conversion โžก๏ธ

โ†’ Implicit (Automatic) ๐Ÿค–

Python automatically converts types during operations:

Python

result = 3 + 4.5    # int(3) โ†’ float, result=7.5 (float)

โ†’ Explicit (Manual) โœ๏ธ

Programmer specifies the conversion:

Python

age = "25"
years_to_100 = 100 - int(age)  # Explicit str โ†’ int

Key Rules & Errors ๐Ÿšจ

  1. Compatibility:Python# int("12.3") # โŒ ValueError (float string โ†’ int) print(float("12.3")) # โœ… 12.3
  2. Collections:Python# list(123) # โŒ TypeError (int not iterable)
  3. Dictionary Conversion:Requires iterable of key-value pairs:Pythonprint(dict([('a', 1), ('b', 2)])) # โœ… Valid # dict([1, 2, 3]) # โŒ TypeError (not key-value pairs)

Practical Example ๐Ÿ’ก

Python

# Calculate average from user input (str โ†’ float)
scores = ["85.5", "90", "78.5"]
numeric_scores = [float(score) for score in scores]  # Convert list of str to float
average = sum(numeric_scores) / len(numeric_scores)
print(f"Average: {average:.2f}")  # Output: Average: 84.67

Mastering type conversions is essential for data processing and user input handling! ๐Ÿš€

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *