Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python regex - Check whether the input is Floating point number or not
Floating point numbers play a crucial role in various programming tasks, from mathematical computations to data analysis. When working with user input or data from external sources, it becomes essential to validate whether the input is a valid floating point number. Python's regular expressions provide a powerful tool to tackle this challenge.
In this article, we will explore how to use regular expressions in Python to check whether the input is a floating point number. Regular expressions, commonly known as regex, offer a concise and flexible way to define patterns and search for matches within text.
Understanding Floating Point Numbers
Floating point numbers are a data type used to represent real numbers in computer systems. They are called "floating point" because the decimal point can "float" to represent numbers of different magnitudes. In Python, floating point numbers are represented using the float data type.
Floating point numbers can have both integer and fractional parts, and they can be positive or negative. They are typically written in the form m.n, where m represents the integer part and n represents the fractional part. For example, 3.14 and -0.5 are valid floating point numbers.
Regular Expression Pattern for Float Validation
To validate a floating point number using a regular expression, we need to define a pattern that matches the expected format. Here are the key components of the pattern:
- Optional sign The number may start with an optional positive (+) or negative () sign.
- Integer part The number can have an optional integer part, which may consist of one or more digits.
- Decimal point The number may contain an optional decimal point (.) to separate the integer and fractional parts.
- Fractional part The number can have an optional fractional part, which consists of one or more digits.
- Exponent The number may have an optional exponent part, denoted by 'e' or 'E' followed by an optional sign and one or more digits.
Python Implementation
Here's a complete Python program that uses regular expressions to check whether an input is a floating point number:
import re
def is_float(input_string):
# Pattern explanation:
# ^ - Start of string
# [-+]? - Optional sign (+ or -)
# [0-9]*\.?[0-9]+ - Digits with optional decimal point
# ([eE][-+]?[0-9]+)? - Optional exponent notation
# $ - End of string
pattern = r'^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?$'
match = re.match(pattern, input_string)
return match is not None
# Test the function
test_inputs = ["3.14", "-0.5", "10.0", "abc", "1.23e-4", ".5", "5.", "1e10"]
for test_input in test_inputs:
result = is_float(test_input)
print(f"'{test_input}' is float: {result}")
'3.14' is float: True '-0.5' is float: True '10.0' is float: True 'abc' is float: False '1.23e-4' is float: True '.5' is float: True '5.' is float: True '1e10' is float: True
Alternative Approach with Exception Handling
While regex provides precise control over the pattern, Python also offers a simpler approach using exception handling:
def is_float_simple(input_string):
try:
float(input_string)
return True
except ValueError:
return False
# Test both approaches
test_cases = ["3.14", "-0.5", "10", "abc", "1.23e-4", ""]
print("Input\t\tRegex\tBuilt-in")
print("-" * 35)
for test in test_cases:
regex_result = is_float(test)
builtin_result = is_float_simple(test)
print(f"'{test}'\t\t{regex_result}\t{builtin_result}")
Input Regex Built-in ----------------------------------- '3.14' True True '-0.5' True True '10' True True 'abc' False False '1.23e-4' True True '' False False
Pattern Breakdown
Let's break down the regular expression pattern r'^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?$':
-
^Matches the start of the string -
[-+]?Optional plus or minus sign -
[0-9]*Zero or more digits (integer part) -
\.?Optional decimal point -
[0-9]+One or more digits (required) -
([eE][-+]?[0-9]+)?Optional exponent notation -
$Matches the end of the string
Comparison
| Method | Pros | Cons |
|---|---|---|
| Regular Expression | Precise control, custom validation rules | More complex, requires regex knowledge |
| Exception Handling | Simple, leverages Python's built-in parsing | Less control, relies on Python's float() function |
Conclusion
Regular expressions provide a powerful way to validate floating point numbers with precise control over the accepted format. While Python's built-in float() function with exception handling offers a simpler approach, regex gives you the flexibility to define custom validation rules for specific use cases.
