0

I know there are ways to check if str can be converted using try-except or regular expressions, but I was looking for (for example) str methods such as

str.isnumeric()
str.isdigit()
str.isdecimal() # also doesn't work for floats

but could't find any. Are there any I haven't found yet?

  • 2
    This should help you [question](https://stackoverflow.com/questions/354038/how-do-i-check-if-a-string-is-a-number-float) – andondraif Oct 14 '20 at 00:49
  • 1
    Does this answer your question? [Checking if a string can be converted to float in Python](https://stackoverflow.com/questions/736043/checking-if-a-string-can-be-converted-to-float-in-python) – PM 77-1 Oct 14 '20 at 00:50
  • @PM77-1 I know how to convert to floats, the question was more of whether there are built-in functions or what is the best way to convert, but as @'andondraif' pointed out it seems try-except is the best way possible – Antonio Margaretti Oct 14 '20 at 00:57
  • Sounds like you are looking for string methods to check types? Here is the documentation: https://docs.python.org/3/library/stdtypes.html#str.isalnum – Frank Oct 14 '20 at 02:44

3 Answers3

2

I would suggest the ask for forgiveness not permission approach of using the try except clause:

str_a = 'foo'
str_b = '1.2'

def make_float(s):
    try:
        return float(s)
    except ValueError:
        return f'Can't make float of "{s}"'

>>> make_float(str_a)
Can't make float of "foo"
>>> make_float(str_b)
1.2
Jab
  • 26,853
  • 21
  • 75
  • 114
  • 2
    Absolutely. This is The Python Way. From the Python glossary: "Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements. The technique contrasts with the LBYL style common to many other languages such as C." – Frank Yellin Oct 14 '20 at 01:27
1

As stated by and Macattack and Jab, you could use try except, which you can read about in python's docs or w3school's tutorial.

Try Except clauses have the form:

try:
    # write your code
    pass
except Exception as e: # which can be ValueError, or other's exceptions
    # deal with Exception, and it can be called using the variable e
    print(f"Exception was {e}") # python >= 3.7
    pass
except Exception as e: # for dealing with other Exception
    pass
# ... as many exceptions you would need to handle
finally:
    # do something after dealing with the Exception
    pass

For a list of built-in Exceptions, see python's docs.

Felipe Whitaker
  • 470
  • 3
  • 9
0

Easiest way would be to just try and turn it into a float.

try:
    float(str)
except ValueError:
    # not float
else:
    # is float
Macattack
  • 1,917
  • 10
  • 15