I just started learning my first real programming language, Python. I'd like to know how to constrain user input in a raw_input
to certain characters and to a certain length. For example, I'd like to show an error message if the user inputs a string that contains anything except the letters a-z
, and I'd like to show one of the user inputs more than 15 characters.
The first one seems like something I could do with regular expressions, which I know a little of because I've used them in Javascript things, but I'm not sure how to use them in Python. The second one, I'm not sure how to approach it. Can anyone help?
This question is related to
python
string
limit
user-input
We can use assert
here.
def _input(inp_str:str):
try:
assert len(inp_str)<=15,print('More than 15 characters present')
assert all('a'<=i<='z' for i in inp_str),print('Characters other than "a"-"z" are found')
return inp_str
except Exception as e:
pass
_input('abcd')
#abcd
_input('abc d')
#Characters other than "a"-"z" are found
_input('abcdefghijklmnopqrst')
#More than 15 characters present
Regexes can also limit the number of characters.
r = re.compile("^[a-z]{1,15}$")
gives you a regex that only matches if the input is entirely lowercase ASCII letters and 1 to 15 characters long.
if any( [ i>'z' or i<'a' for i in raw_input]):
print "Error: Contains illegal characters"
elif len(raw_input)>15:
print "Very long string"
Source: Stackoverflow.com