简体   繁体   English

如何限制字符串中的字母数量

[英]How do I limit the amount of letters in a string

I have a program that asks a the user to input a question, the program then answers it. 我有一个程序要求用户输入一个问题,程序然后回答它。 What I want to know is how do I limit the amount of letters a user can input into a variable. 我想知道的是如何限制用户输入变量的字母数量。

Python's input function cannot do this directly; Python的input函数不能直接执行此操作; but you can truncate the returned string, or repeat until the result is short enough. 但您可以截断返回的字符串,或重复直到结果足够短。

# method 1
answer = input("What's up, doc? ")[:10]  # no more than 10 characters

# method 2
while True:
    answer = input("What's up, doc? ")
    if len(answer) <= 10:
        break
    else:
        print("Too much info - keep it shorter!")

If that's not what you're asking, you need to make your question more specific. 如果那不是您要求的,那么您需要更具体地提出问题。

您只能获得输入文本的前n个字符,如下所示:

data = raw_input()[:10]

use this: 用这个:

while True:
    answer = input("What's up, doc? ")
    if len(answer) >= 10:
        print("Too much info - keep it shorter!")

You can check it with builtin len function: 您可以使用内置len函数进行检查:

my_input = raw_input("Enter something ")
if len(my_input) > 3:
  print "More then 3"
else:
  print "Ok"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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