Python Program to Parse a String to a Float or Int


10xer.co Ad Sponsored

ⓘ Sponsored by 10xer.co

In Python, there are three main data types used for numbers and text: strings, floats, and integers.

  1. Strings: A string is a sequence of characters enclosed within single quotes (’ ‘) or double quotes (" “). Strings are immutable, meaning their values cannot be changed once they are created. Strings are used to represent text and are commonly used for displaying messages, labels, or data. Example:

my_string = "Hello, World!"

  1. Floats: A float is a number with a decimal point. Floats are used to represent real numbers, including numbers with fractional values. Floats are stored in memory using a fixed number of bytes, which limits their precision. Floats can be created by directly assigning a value with a decimal point or by performing a calculation that results in a decimal value. Example:

my_float = 3.14

  1. Integers: An integer is a whole number, meaning it has no decimal point. Integers are used to represent counts, quantities, and indices. They can be positive, negative, or zero. Integers can be created by directly assigning a value or by performing a calculation that results in a whole number. Example:

my_int = 42


Python Code :

The below Python program parses a string to a float or int:


def parse_number(s):
    """
    Parse a string to a float or int.

    Args:
        s: The string to parse.

    Returns:
        A float or int if the string can be parsed to one, or None if it cannot.
    """
    try:
        number = float(s)
        if number.is_integer():
            return int(number)
        else:
            return number
    except ValueError:
        return None

# Example usage
string1 = "123"
string2 = "3.14159"
string3 = "not a number"
num1 = parse_number(string1)
num2 = parse_number(string2)
num3 = parse_number(string3)
print(num1) # Output: 123
print(num2) # Output: 3.14159
print(num3) # Output: None


In this program, we define a function parse_number that takes a string s as input. We attempt to parse the string to a float using a try-except block. If parsing to a float is successful, we check if the number is an integer using the is_integer() method. If it is, we return the integer value. If it’s not, we return the float value.

If parsing to a float is not successful, we return None.

In the example usage, we call the parse_number function with three different strings: one that can be parsed to an integer, one that can be parsed to a float, and one that cannot be parsed to a number. The resulting parsed numbers are then printed to the console. Output:


123
3.14159
None


10xer.co Ad Sponsored

ⓘ Sponsored by 10xer.co