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

  • Combined Character Classes

    Combined Character Classes Explained with Examples 1. [a-zA-Z0-9_] – Word characters (same as \w) Description: Matches any letter (lowercase or uppercase), any digit, or underscore Example 1: Extract all word characters from text python import re text = “User_name123! Email: test@example.com” result = re.findall(r'[a-zA-Z0-9_]’, text) print(result) # [‘U’, ‘s’, ‘e’, ‘r’, ‘_’, ‘n’, ‘a’, ‘m’, ‘e’, ‘1’, ‘2’,…

  • Anchors (Position Matchers)

    Anchors (Position Matchers) in Python Regular Expressions – Detailed Explanation Basic Anchors 1. ^ – Start of String/Line Anchor Description: Matches the start of a string, or start of any line when re.MULTILINE flag is used Example 1: Match at start of string python import re text = “Python is great\nPython is powerful” result = re.findall(r’^Python’, text) print(result) #…

  • What are Variables

    A program is essentially a set of instructions that tells a computer what to do. Just like a recipe guides a chef, a program guides a computer to perform specific tasksβ€”whether it’s calculating numbers, playing a song, displaying a website, or running a game. Programs are written in programming languages like Python, Java, or C++,…

  • String Validation Methods

    Complete List of Python String Validation Methods Python provides several built-in string methods to check if a string meets certain criteria. These methods return True or False and are useful for input validation, data cleaning, and text processing. 1. Case Checking Methods Method Description Example isupper() Checks if all characters are uppercase “HELLO”.isupper() β†’ True islower() Checks if all…

  • Python Modules: Creation and Usage Guide

    Python Modules: Creation and Usage Guide What are Modules in Python? Modules are simply Python files (with a .py extension) that contain Python code, including: They help you organize your code into logical units and promote code reusability. Creating a Module 1. Basic Module Creation Create a file named mymodule.py: python # mymodule.py def greet(name): return f”Hello, {name}!”…

  • Programs

    Weekly Wages Removing Duplicates even ,odd Palindrome  Rotate list Shuffle a List Python random Module Explained with Examples The random module in Python provides functions for generating pseudo-random numbers and performing random operations. Here’s a detailed explanation with three examples for each important method: Basic Random Number Generation 1. random.random() Returns a random float between 0.0 and 1.0 python import…

Leave a Reply

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