Search code examples
pythonraw-input

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.


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.