DEV Community

Cover image for Python Type Conversion Made Simple ( int, str, bool & lists)
Mary Nyandia
Mary Nyandia

Posted on

Python Type Conversion Made Simple ( int, str, bool & lists)

On my sixth day of learning Python, I explored type conversion, the process of changing data from one type to another. This is super important because sometimes you’ll need to work with numbers, strings, or booleans in different ways, and Python makes it easy to switch between them.

1. πŸ“₯ Converting Strings to Integers

number_str = "100"
number_int = int(number_str)
print("String to int:", number_int, type(number_int))

Enter fullscreen mode Exit fullscreen mode

Here, "100" is a string (text), but by using int(), Python converts it into the number 100. This is useful when you’re reading numbers from user input or files, which often come in as text.

2. πŸ“€ Converting Floats to Strings

float_value = 12.34
number_str2 = str(float_value)
print("Float to string:", number_str2, type(number_str2))

Enter fullscreen mode Exit fullscreen mode

The number 12.34 is a float (decimal), but str() turns it into "12.34". This is handy when you want to display numbers as part of a message or save them in text format.

3. βœ… Converting Booleans to Integers

boolean_value = True
number_from_bool = int(boolean_value)
print("Bool to int:", number_from_bool)

Enter fullscreen mode Exit fullscreen mode

Booleans (True or False) can be converted into integers: True becomes 1 and False becomes 0. This is useful when you want to use logical values in calculations.

4. πŸ“š Converting Lists of Strings to Integers

values = ["1", "2", "3"]
ints = [int(x) for x in values]
print("Converted list:", ints)

Enter fullscreen mode Exit fullscreen mode

Here, we used a list comprehension to convert each string in the list into an integer. The result is [1, 2, 3]. This technique is powerful when cleaning or preparing data for analysis.

🎯My Take
Type conversion is all about flexibility. It allows you to:

  • Turn text into numbers for calculations.
  • Turn numbers into text for display.
  • Use booleans as numbers in logic.
  • Transform entire lists of values at once.

Mastering type conversion ensures your program can handle data in the right format at the right time.

Top comments (0)