我有一个程序,要求用户输入一个问题,然后程序回答它。
我想知道的是如何限制用户可以输入到变量中的字母数量。

最佳答案

Python 的 input 函数不能直接做到这一点;但是你可以截断返回的字符串,或者重复直到结果足够短。

# 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!")

如果这不是您要问的问题,则需要使您的问题更具体。

关于python - 如何限制字符串中的字母数量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28465779/

10-13 02:12