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

  • Lambda Functions in Python

    Lambda Functions in Python Lambda functions are small, anonymous functions defined using the lambda keyword. They can take any number of arguments but can only have one expression. Basic Syntax python lambda arguments: expression Simple Examples 1. Basic Lambda Function python # Regular function def add(x, y): return x + y # Equivalent lambda function add_lambda =…

  • recursive function

    A recursive function is a function that calls itself to solve a problem. It works by breaking down a larger problem into smaller, identical subproblems until it reaches a base case, which is a condition that stops the recursion and provides a solution to the simplest subproblem. The two main components of a recursive function…

  • The print() Function in Python

    The print() Function in Python: Complete Guide The print() function is Python’s built-in function for outputting data to the standard output (usually the console). Let’s explore all its arguments and capabilities in detail. Basic Syntax python print(*objects, sep=’ ‘, end=’\n’, file=sys.stdout, flush=False) Arguments Explained 1. *objects (Positional Arguments) The values to print. You can pass multiple items separated by commas. Examples:…

  •  List Comprehensions 

    List Comprehensions in Python (Basic) with Examples List comprehensions provide a concise way to create lists in Python. They are more readable and often faster than using loops. Basic Syntax: python [expression for item in iterable if condition] Example 1: Simple List Comprehension Create a list of squares from 0 to 9. Using Loop: python…

  • Polymorphism

    Polymorphism is a core concept in OOP that means “many forms” 🐍. In Python, it allows objects of different classes to be treated as objects of a common superclass. This means you can use a single function or method to work with different data types, as long as they implement a specific action. 🌀 Polymorphism…

  • positive lookahead assertion

    A positive lookahead assertion in Python’s re module is a zero-width assertion that checks if the pattern that follows it is present, without including that pattern in the overall match. It is written as (?=…). The key is that it’s a “lookahead”—the regex engine looks ahead in the string to see if the pattern inside…

Leave a Reply

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