One of the most notable breakthrough that Python brought was that the interconversion between the datatypes was done in a very easy manner and hence making it quite powerful. String can be converted to integers easily, but converting a float value is still difficult task. Let’s discuss certain ways in which one can check if string is a float to avoid potential errors.
Method #1 : Using isdigit() + replace() The combination of above function is used to perform this task and hence. This works in 2 steps, first the point value is erased and the string is joined to form a digit and then is checked. The drawback is that this doesn’t check for potential exponent values that can also form a float number.
# Python3 code to demonstrate # Check for float string # using isdigit() + replace() # initializing string test_string = "45.657"
# printing original string print ( "The original string : " + str (test_string))
# using isdigit() + replace() # Check for float string res = test_string.replace( '.' , '', 1 ).isdigit()
# print result print ( "Is string a possible float number ? : " + str (res))
|
The original string : 45.657 Is string a possible float number ? : True
Time Complexity: O(1)
Auxiliary Space: O(1)
Method #2 : Using float() + Exception handling This task can also be achieved using the float function which tries to convert the string to floating point value, and it’s failure guarantees that it’s not potential float value.
# Python3 code to demonstrate # Check for float string # using float() # initializing string test_string = "45.657"
# printing original string print ( "The original string : " + str (test_string))
# using float() # Check for float string try :
float (test_string)
res = True
except :
print ( "Not a float" )
res = False
# print result print ( "Is string a possible float number ? : " + str (res))
|
The original string : 45.657 Is string a possible float number ? : True
Method #3: Using regex
This method uses a regular expression to check if the string is a valid float.
import re
def is_float(string):
# Compile a regular expression pattern to match valid float values
pattern = r "^[-+]?[0-9]*\.?[0-9]+$"
# Use re.match to check if the string matches the pattern
# Returns a match object if there is a match, else None
match = re.match(pattern, string)
# Convert the match object to a boolean value
# Returns True if there is a match, else False
return bool (match)
test_string = "45.657"
# Printing the original string print ( "The original string : " + str (test_string))
# Check if the string is a float and print the result result = is_float(test_string)
print ( "Is string a possible float number ? : " + str (result))
#This code is contributed by Edula Vinay Kumar Reddy |
The original string : 45.657 Is string a possible float number ? : True
Time complexity: O(n), where n is the length of the string.
Auxiliary space: O(1), since the regex pattern is a constant size.
Method #4: Using regular expression without anchors and allowing exponent notation
Step-by-step approach:
- Define a function named is_float_v2 that takes a string as input.
- Create a regular expression pattern that matches valid float values with optional exponent notation:
* [-+]? matches an optional sign (+ or -).
* \d+ matches one or more digits before the decimal point.
* (\.\d*)? matches an optional decimal point followed by zero or more digits after it.
* |\.\d+ matches a decimal point followed by one or more digits after it.
* ([eE][-+]?\d+)? matches an optional exponent notation with an optional sign followed by one or more digits. - Use re.match to check if the string matches the pattern.
- Convert the match object to a boolean value using bool():
If there is a match, re.match returns a match object, which is truthy.
If there is no match, re.match returns None, which is falsy. - Return the boolean value indicating whether or not the input string is a valid float.
- Define a test string named test_string.
- Print the original test string using print.
- Call the is_float_v2 function with test_string as the input and store the result in a variable named result.
- Print the result of the function using print.
import re
def is_float_v2(string):
pattern = r "[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?"
match = re.match(pattern, string)
return bool (match)
test_string = "45.657"
print ( "The original string: " + str (test_string))
result = is_float_v2(test_string)
print ( "Is string a possible float number? : " + str (result))
|
The original string: 45.657 Is string a possible float number? : True
Time complexity: O(n), where n is the length of the string.
Auxiliary Space: O(1), as it only uses a constant amount of additional space.