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))
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))
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)
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)
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)