w3resource

Python: Parse a string to Float or Integer

Python Basic: Exercise-48 with Solution

Write a Python program to parse a string to float or integer.

Sample Solution-1:

Python Code:

# Define a string 'n' containing a numeric value.
n = "246.2458"

# Convert the string 'n' to a floating-point number and print the result.
print(float(n))

# Convert the floating-point number to an integer, truncating any decimal part, and print the result.
print(int(float(n)))

Sample Output:

246.2458                                                                                                      
246 

Explanation:

float(x=0.0) : Returns a floating point number constructed from a number or string x.

If the argument is a string, it should contain a decimal number, optionally preceded by a sign, and optionally embedded in whitespace. The optional sign may be '+' or '-'; a '+' sign has no effect on the value produced. The argument may also be a string representing a NaN (not-a-number), or positive or negative infinity.

The above Python code creates a variable n with the value "246.2458" as a string. The float() function is used to convert the string "246.2458" to a floating-point number. The print() function is then used to output this floating-point number to the console.

Sample Solution-2:

Python Code:

# Define a function 'test' that takes a string 's' as input.
def test(s):
    try:
        # Try to convert the input string to an integer.
        return int(s)
    except ValueError:
        # If the conversion to an integer raises a ValueError (i.e., it's not an integer), 
        # then try to convert the string to a floating-point number (float).
        return float(s)

# Call the 'test' function with different input values and print the results.
print(test('12'))       # Try to convert '12' to an integer.
print(test('233.12'))   # Try to convert '233.12' to a float.

Sample Output:

12
233.12

Python Code Editor:

 

Previous: Write a Python program to find out the number of CPUs using.
Next: Write a Python program to list all files in a directory in Python.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.