/  Technology   /  How do I parse a string to a float or int in Python?
How do I parse a string to a float or int in Python

How do I parse a string to a float or int in Python?

 

Python supports Type conversion using which we can convert from one datatype to another real quick. 

 

Parsing string into int:

We can convert a string type object to an integer type object using the int() function. We pass the string as a parameter to this function. 

 

Let’s take an example where we stored the string in a variable named our_input_string. We pass this to the int() function and store it in another variable named converted_int. If we check the type of this converted_list, it returns an integer object.

Example:

our_input_str = "1000"
print("The input string is:",our_input_str)

converted_int = int(our_input_str)
print("Type:", type(converted_int))

print("The integer is: ",converted_int)

Output:

Note: The string passed must definitely be a number.

 

Parsing string into float:

The float() function can be used to convert a string type object to a float type object. It works similar to the int() function.

Example:

our_input_str = "1000.444"
print("The input string is:",our_input_str)

converted_int = float(our_input_str)
print("Type:", type(converted_int))

print("The integer is: ",converted_int)

Output:

 

Parsing a string float number into integer:

We can accomplish this using the below syntax:

int(float(any_string))

Example:

int(float(any_string))


our_input_str = "1000"
print("The input string is:",our_input_str)

converted_int = int(float(our_input_str))
print("Type:", type(converted_int))

print("The integer is: ",converted_int)

Output:

How do I parse a string to a float or int in python

 

Leave a comment