Why converting numeric string type to integer or float type in Python?
In Python, converting a numeric string to an integer or a float is often necessary for the following reasons:
Mathematical Expressions: To perform numerical operations on the data and use it in mathematical expressions.
Data Comparison: To compare or sort data, it's essential to convert numeric string type to integer or float type to make meaningful comparisons.
Converting numeric string to integer using int() function
In Python, you can convert a numeric string type to an integer type using int()
built-in function.
In the following example, numeric string "1225"
is converted to integer type using int() function. Then 25
is added to the integer variable 'converted_string_to_integer'
to perform mathematical operation.
Please take a closer look at the following example:
Example of int() function
Output of the above example
The sum of 1225 and 25 is 1250
Converting numeric string to float using float() function
In Python, you can convert a numeric string type to a float type using float()
built-in function.
In the following example, numeric string "1225.50"
is converted to float type using float() function. Then 25.50
is added to the float variable 'converted_string_to_float'
to perform mathematical operation.
Please take a closer look at the following example:
Example of float() function
Output of the above example
The sum of 1225.50 and 25.50 is 1251.0