Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limiting Python input strings to certain characters and lengths

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?

like image 524
kidosu Avatar asked Jan 06 '12 17:01

kidosu


People also ask

How do you restrict string length in Python?

To limit user input length: Use a while loop to iterate until the user enters a string of the specified length. Check if the user entered a message of the given length.

How do I set the length of an input in Python?

you can use getkey() or getstr(). but using getstr() is simpler, and it give the user choice to enter less than 5 char if he want, but no more than 5.

How do you make input only accept letters in Python?

To only allow letters when taking user input: Use a while loop to iterate until the user enters only letters. Use the str. isalpha() method to check if the user entered only letters.


1 Answers

Question 1: Restrict to certain characters

You are right, this is easy to solve with regular expressions:

import re

input_str = raw_input("Please provide some info: ")
if not re.match("^[a-z]*$", input_str):
    print "Error! Only letters a-z allowed!"
    sys.exit()

Question 2: Restrict to certain length

As Tim mentioned correctly, you can do this by adapting the regular expression in the first example to only allow a certain number of letters. You can also manually check the length like this:

input_str = raw_input("Please provide some info: ")
if len(input_str) > 15:
    print "Error! Only 15 characters allowed!"
    sys.exit()

Or both in one:

import re

input_str = raw_input("Please provide some info: ")
if not re.match("^[a-z]*$", input_str):
    print "Error! Only letters a-z allowed!"
    sys.exit()
elif len(input_str) > 15:
    print "Error! Only 15 characters allowed!"
    sys.exit()

print "Your input was:", input_str
like image 114
Niklas B. Avatar answered Sep 20 '22 13:09

Niklas B.