2

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.

2

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

It shouldn't depend on the implementation, it should depend on which gives the better user experience
I mean, what depends on the implementation is the way he will handle the input. If OP wants to reprompt for input if it has more than 40 characters, use @bigblind or @ JoranBeasley approaches.
2

try this:

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

1 Comment

Thanks @Alex Thornton, we tried to make the same edit at the same time :p
1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.