Python – Check for float string
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.
s = "123.45"
try:
val = float(s)
print("Valid float")
except ValueError:
print("Invalid float")
Output
Valid float
Explanation:
tryblock attempts to convert the stringsinto a float using thefloat()function.- If the conversion fails and raises a
ValueError, theexceptblock 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.
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 stringsmatches 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


