Python Program to Parse a String to a Float or Int – 2024

Hey guys, in this blog we will see a Python Program to Parse a String to a Float or Int.

Example 1: Parse a string into an integer

# Python Program to Parse a String to a Float or Int

balance_str = "1800"
balance_int = int(balance_str)

# print the type
print(type(balance_int))

# print the value
print(balance_int)

Output

<class 'int'>
1800
  • Using the inbuilt method int() to convert a string to an int.

Example 2: Parse a string into float

balance_str = "1800.8"
balance_float = float(balance_str)

# print the type
print(type(balance_float))

# print the value
print(balance_float)

Output

<class 'float'>
1800.8
  • Using the inbuilt method float() to convert a string to a float.

Example 3: A string float numeral into an integer

balance_str = "1800.29"
balance_int = int(float(balance_str))

# print the type
print(type(balance_int))

# print the value
print(balance_int)

Output

<class 'int'>
1800
  • We are first converting it to float using float() and then int using int().

Check out our other python programming examples

Leave a Reply

Your email address will not be published. Required fields are marked *