Blacksilver Blacksilver - 2 months ago 11
Python Question

Check if a var is a string of numbers

o/

i am making a small interactive text game in python.

i need to check if a string, from the user, is '1234' (a number in a string, one that would work with int() ) or 'foo' (just a string)

def setamount(PYR)#for controlcolum
IN = standardin("Set To: ")
# if var IN is a string containing numbers:
if (PYR = pitch_yaw_roll[1]):
#whatever i do here
if (PYR = pitch_yaw_roll[2]):
#whatever i do here
if (PYR = pitch_yaw_roll[3]):
#whatever i do here
#/if
# if it's not:
standardunknown()


so yeah
thanks in advance

EDIT: i know there are errors in this code, i usually let the compiler check then fix it.
EDIT (again): standard in is input(">>") so i never typo the '(>>)' part (unless i give it a string in which case it uses that string in input())and standardunknown() is Print("???") so i never typo that either. (im OCD about consistency)

Answer

If you want to know if something is "a number in a string, one that would work with int()", you do that by just calling int:

try:
    i = int(myvar)
    # It's an int, and we have the value if you want it
except ValueError:
    # It's not an int

This is a general case of the EAFP principle: It's Easier to Ask Forgiveness than Permission. Instead of trying to guess whether something would fail, it's usually easier to just try it and see if it fails.

That's especially try in cases where trying to guess is more complicated than it looks. For example, people always suggest using the isdigit method here, but that fails in a number of cases. For example:

  • isdigit is false for negative numbers, because the '-' character is not a digit.
  • isdigit is false for numbers with trailing whitespace (e.g., because you're not rstripping newlines from your input).
  • isdigit is true for hundreds of non-western digits and special-form digits that can't be used with int.
  • int has changed its rules at least twice between Python 2.0 and 3.4, and could always change again.

You probably could come up with a complicated rule that was exactly the same as "would work with int()" as interpreted in some specific Python version, but why, when int is obviously guaranteed to always do the same thing as int?

Comments