简体   繁体   中英

Limiting raw_input in python

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.

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM