Question

How can I limit the amount of characters that a user will be able to type into raw_input? There is probably some easy solution to my problem, but I just can't figure it out.

Was it helpful?

Solution

A simple solution will be adding a significant message and then using slicing to get the first 40 characters:

some_var = raw_input("Input (no longer than 40 characters): ")[:40]

Another would be to check if the input length is valid or not:

some_var = raw_input("Input (no longer than 40 characters): ")

if len(some_var) < 40:
    # ...

Which should you choose? It depends in your implementation, if you want to accept the input but "truncate" it, use the first approach. If you want to validate first (if input has the correct length) use the second approach.

OTHER TIPS

try this:

while True:
    answer = raw_input("> ")
    if len(answer) < 40:
        break
    else:
        print("Your input should not be longer than 40 characters")

I like to make a general purpose validator

def get_input(prompt,test,error="Invalid Input"):
    resp = None
    while True:
         reps = raw_input(prompt)
         if test(resp):
            break
         print(error)
    return resp

x= get_input("Enter a digit(0-9):",lambda x:x in list("1234567890"))
x = get_input("Enter a name(less than 40)",lambda x:len(x)<40,"Less than 40 please!")
x = get_input("Enter a positive integer",str.isdigit)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top