rwjones
rwjones

Reputation: 377

Distinguishing a string from a string representation

Python 3.4

I am writing a validation function to check a user's input. In one case I'm trying to validate the user entered an integer between 0 and 99.

Everything comes in as a string, and so assuming we have a string representation of an integer, the obvious place to start is with something like:

isinstance(int(userinput), int)

But assuming there is no end to the ways a user can make a mistake, suppose he or she enters '2l' by accident. This is actually a string, not a string representation of an integer. The above isinstance() check on this results in:

ValueError: invalid literal for int() with base 10: '2l'

I can't figure out how to account for this possibility.

Upvotes: 1

Views: 61

Answers (2)

jpcgt
jpcgt

Reputation: 2248

You can check for an arbitrary syntax with regular expressions. For a sequence of digits:

import re

match = re.search('\d+', userinput)
if match:
    print int(match.group(0))

Upvotes: 0

DeepSpace
DeepSpace

Reputation: 81614

With try and except, and you don't even need the isinstance check:

userinput = None
try:
    userinput = int(input("type a number"))
except ValueError:
    print ("invalid input")

if userinput is not None:
     # rest of code

Upvotes: 5

Related Questions