What are other type conversions?

In Python, there are several common type conversions (also known as type casting) you can perform:

  1. Integer to Float:

    num = 10
    float_num = float(num)  # Converts to 10.0
  2. Float to Integer:

    num = 10.5
    int_num = int(num)  # Converts to 10 (truncates the decimal)
  3. String to Integer:

    num_str = "123"
    int_num = int(num_str)  # Converts to 123
  4. String to Float:

    num_str = "123.45"
    float_num = float(num_str)  # Converts to 123.45
  5. List to Tuple:

    my_list = [1, 2, 3]
    my_tuple = tuple(my_list)  # Converts to (1, 2, 3)
  6. Tuple to List:

    my_tuple = (1, 2, 3)
    my_list = list(my_tuple)  # Converts to [1, 2, 3]
  7. Boolean to Integer:

    bool_val = True
    int_val = int(bool_val)  # Converts to 1
  8. Integer to Boolean:

    int_val = 0
    bool_val = bool(int_val)  # Converts to False

These conversions are useful for manipulating data types as needed in your programs. If you have specific scenarios in mind, feel free to ask!

0 Comments

no data
Be the first to share your comment!