Python Program - Parse a String to a Float or Int
here's a Python program that parses a string to a float
or int
:
# Define a string containing a number num_string = "123.45" # Parse the string to a float using the float() function float_num = float(num_string) # Parse the string to an int using the int() function int_num = int(float_num) # Print the parsed numbers print("Float:", float_num) print("Int:", int_num)
In this program, we define a string called num_string
containing a number ("123.45"
).
To parse the string to a float
, we can use the float()
function, which takes a string as its argument and returns a float
.
We assign the result of float(num_string)
to a variable called float_num
.
To parse the float
to an int
, we can use the int()
function, which takes a number as its argument and returns an int
.
We assign the result of int(float_num)
to a variable called int_num
.
Finally, we can print the parsed numbers using the print()
function and string formatting.
If we run this program, the output will be:
Float: 123.45 Int: 123
Note that the float()
function will raise a ValueError
exception if called with a string that cannot be parsed as a float
. Similarly, the int()
function will raise a ValueError
exception if called with a non-integer or a float
that cannot be represented as an int
. If you need more control over the parsing process, you can use the decimal
module, which provides classes for working with decimal numbers.