The Wayback Machine - https://web.archive.org/web/20250116085220/https://www.geeksforgeeks.org/python-check-for-float-string/
Open In App

Python – Check for float string

Last Updated : 11 Jan, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Checking for float string refers to determining whether a given string can represent a floating-point number. A float string is a string that, when parsed, represents a valid float value, such as “3.14”, “-2.0”, or “0.001”.

For example:

  • “3.14” is a float string.
  • “abc” is not a float string.

Using try-except

try block attempts to create chunks of size k by zipping the string s into tuples and joining them. If any error occurs during this process, the except block catches it and prints an error message. For most cases, float() with exception handling is sufficient.

Python
s = "123.45"

try:
    val = float(s)
    print("Valid float")
except ValueError:
    print("Invalid float")

Output
Valid float

Explanation:

  • try block attempts to convert the string s into a float using the float() function.
  • If the conversion fails and raises a ValueError, the except block catches it and prints “Invalid float”.

Using Regular Expressions

Regular expressions can be used to check if a string matches a valid float pattern, such as "^\d+(\.\d+)?$". If the string matches, it’s considered a valid float; otherwise, it’s invalid. Use regular expressions for stricter validation or when controlling the format is necessary.

Python
import re

s = "123.45"
pattern = r"^-?\d+\.\d+$"  # Regular expression for a valid float

if re.match(pattern, s):
    print("Valid float")
else:
    print("Invalid float")

Output
Valid float

Explanation:

  • regular expression r"^-?\d+\.\d+$" checks if the string s matches the pattern of a valid float, including optional negative signs.
  • If the string matches the pattern, “Valid float” is printed; otherwise, “Invalid float” is printed.

Enhance your coding skills with DSA Python, a comprehensive course focused on Data Structures and Algorithms using Python. Over 90 days, you'll explore essential algorithms, learn how to solve complex problems, and sharpen your Python programming skills. This course is perfect for anyone looking to level up their coding abilities and get ready for top tech interviews.
Join the Three 90 Challenge and commit to completing 90% of the course in 90 days to earn a 90% refund. It’s the perfect way to stay focused, track your progress, and reap the rewards of your hard work. Take the challenge and become a DSA expert in Python today


Next Article
Practice Tags :

Similar Reads

three90RightbarBannerImg