如何限制字符串中的字母数量 [英] 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的 input
函数不能直接执行此操作;但是您可以截断返回的字符串,或者重复执行直到结果足够短为止.
Python's input
function cannot do this directly; 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.
这篇关于如何限制字符串中的字母数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文