Python | Check floating point string



Method # 1: Using isdigit () + replace ()
A combination of the above function is used to accomplish this task and therefore. This works in 2 steps, first the point value is erased and the string is concatenated to form a digit, and then it is verified. The downside is that it does not check for potential exponent values, which can also form a floating point number.

# Python3 demo code
# Check the floating point string
# using isdigit () + replace ()

 
# initialization string

test_string = "45.657"

 
# print the original line

print ( "The original string:" + str (test_ string))

 
# using isdigit () + replace ()
# Check floating point string

res = test_string.replace ( ` .` , ``, 1 ). isdigit ()

 
# print result

print ( "Is string a possible float number? : " + str (res))

Output:

 The original string: 45.657 Is string a possible float number?: True 

Method # 2: Using float () + exception handling
This task can also be performed using a floating point function that tries to convert a string to a floating point value and its failure ensures that it is not a potential floating point value.

# Python3 demo code
# Check the floating point string
# using float ()

 
# initialization string

test_string = "45.657"

  
# print original line

print ( "The original string:" + str (test_string))

 
# using float ()
# Check the 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))

Output:

 The original string: 45.657 Is string a possible float number?: True