Limiting Python input strings to certain characters and lengths
Asked Answered
P

5

18

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?

Pedant answered 6/1, 2012 at 17:21 Comment(0)
U
21

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
Uncial answered 6/1, 2012 at 17:28 Comment(0)
I
15

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.

Iata answered 6/1, 2012 at 17:25 Comment(0)
O
3

We can use assert here.

def custom_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

custom_input('abcd')
#abcd
custom_input('abc d')
#Characters other than "a"-"z" are found
custom_input('abcdefghijklmnopqrst')
#More than 15 characters present

You can build a wrapper around input function.

def input_wrapper(input_func):
    def wrapper(*args, **kwargs):
        inp = input_func(*args, **kwargs)
        if len(inp) > 15:
            raise ValueError("Input length longer than 15")
        elif not inp.isalpha():
            raise ValueError("Non-alphabets found")
        return inp
    return wrapper

custom_input = input_wrapper(input)
Olwen answered 23/2, 2020 at 18:5 Comment(0)
E
0
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"
Electrode answered 6/1, 2012 at 17:28 Comment(0)
C
0

possibly you can get them with importing string to verify the string type:

def enter_sentence():
condition = False
while not condition:
    sentence = input('Enter a sentence please: ').lower()
    lower_check_list = list(string.ascii_lowercase + ' ')
    for letter in sentence:
        if letter not in lower_check_list:
            print('Enter only a letter characters.Try again')
            break
    else:
        if len(sentence) > 15:
            print('The maximum number of characters is 14. Try again')
        else:
            condition = True

return 'Your sentence has been verified and complies'



print(enter_sentence())
Cardiovascular answered 28/7, 2023 at 18:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.