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.
Asked
Active
Viewed 6,664 times
2

Ethan Bierlein
- 3,353
- 4
- 28
- 42
-
possible duplicate of [Limiting Python input strings to certain characters and lengths](http://stackoverflow.com/questions/8761778/limiting-python-input-strings-to-certain-characters-and-lengths) – Ruben Bermudez Apr 06 '14 at 20:14
-
2You either want the duplicate posted by @Ruben or if you want to not allow an input to exceed 40 chars, then you'll need to look at counting it on a char by char basis, see: http://stackoverflow.com/questions/510357/python-read-a-single-character-from-the-user – Jon Clements Apr 06 '14 at 20:18
3 Answers
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.

Christian Tapia
- 33,620
- 7
- 56
- 73
-
It shouldn't depend on the implementation, it should depend on which gives the better user experience – Bryan Oakley Apr 06 '14 at 20:21
-
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. – Christian Tapia Apr 06 '14 at 20:25
2
try this:
while True:
answer = raw_input("> ")
if len(answer) < 40:
break
else:
print("Your input should not be longer than 40 characters")

anon582847382
- 19,907
- 5
- 54
- 57

bigblind
- 12,539
- 14
- 68
- 123
-
Thanks @Alex Thornton, we tried to make the same edit at the same time :p – bigblind Apr 06 '14 at 20:19
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)

Joran Beasley
- 110,522
- 12
- 160
- 179