This tutorial shows examples to extract the float value from a string in Python.
Example: Extract Float Value from a String in Python
Suppose you have a number of strings similar to Current Level: 4.89 db.
and you want to extract just the floating-point number.
user_input = "Current Level: 4.89 db" for token in user_input.split(): try: print (float(token), "is a float") except ValueError: print (token, "is something else")
Output:
Current is something else Level: is something else 4.89 is a float db is something else
Example 2: Using re Library
import re re.findall("\d+\.\d+", "Current Level: 47.5 db.")
Output:
['47.5']
Reference:Â Extract float from a string in Python.