Type Conversion in Python (With Examples):


In Python, type conversion is a process of changing the data type of a variable from one type to another. This is a common operation in programming when working with data of different types. 

Python supports several built-in functions for type conversion, including int(), float(), str(), and bool().

Converting to integer:

In this process, we can convert a variable to an integer, and use the int() function.

a = "10"
b = int(a)
# Output: 10

Converting to float:

To convert a variable to a floating-point number, use the float() function.

a = "3.14"
b = float(a)
# Output: 3.14

Converting to a string:

To convert a variable to a string, use the str() function.

a = 10
b = str(a)
# Output: "10"

Converting to boolean:

To convert a variable to a boolean, use the bool() function.

a = "True"
b = bool(a)
# Output: True

Note that not all values can be converted to a boolean. In Python, the following values are considered False: False, None, 0, and empty sequences (e.g., “”, [], {}).

In addition to these built-in functions, Python also provides a way to create user-defined functions for type conversion. 

If you want to get more information about Python Fundamentals you can visit here.

These functions can be used to convert data types that are not covered by the built-in functions or to perform more complex conversions.

Was this helpful?

Related Articles:

Recent Articles:

0 0 votes
Article Rating
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x