str is a string s is a string
() All characters are numeric or alphabetic
() All characters are letters
() All characters are numbers
() All characters are blank characters, t, n, r
Checking that a string is a number/float method
float part
>> float('Nan') nan >> float('Nan') nan >> float('nan') nan >> float('INF') inf >> float('inf') inf >> float('-INF') inf >> float('-inf') inf
The first: the simplest
def is_number(str): try: # Because the one exception to using floats is 'NaN' if str=='NaN': return False float(str) return True except ValueError: return False floatillustrative example of an exception >>> float('NaN') nan
Using complex()
def is_number(s): try: complex(s) # for int, long, float and complex except ValueError: return False return True
Synthesis 1
def is_number(s): try: float(s) # for int, long and float except ValueError: try: complex(s) # for complex except ValueError: return False return True
Composite 2 - still not fully recognized
def is_number(n): is_number = True try: num = float(n) # Check "nan" is_number = num == num # Or use `(num)` except ValueError: is_number = False return is_number >>> is_number('Nan') False >>> is_number('nan') False >>> is_number('123') True >>> is_number('-123') True >>> is_number('-1.12') True >>> is_number('abc') False >>> is_number('inf') True
The second: can only be judged as an integer
Using isnumeric()
# str must be uniconde mode >>> str = u"345" >>> ()True /python/string_isnumeric.htm /2/howt...
Using isdigit()
/2/lib... >>> str = "11" >>> print () True >>> str = "3.14" >>> print () False >>> str = "aaa" >>> print () False
Using int()
def is_int(str): try: int(str) return True except ValueError: return False
Third: use regular (safest method)
import re def is_number(num): pattern = (r'^[-+]?[-0-9]\d*\.\d*|[-+]?\.?[0-9]\d*$') result = (num) if result: return True else: return False >>>: is_number('1') True >>>: is_number('111') True >>>: is_number('11.1') True >>>: is_number('-11.1') True >>>: is_number('inf') False >>>: is_number('-inf') False
summarize
The above is a small introduction to Python to determine whether the string is a letter or a number (floating point) of the various methods, I hope to help you, if you have any questions please leave me a message, I will reply to you in a timely manner. Here also thank you very much for your support of my website!