Python 如何让用户一次只输入一个字符

Python 如何让用户一次只输入一个字符,python,Python,好的,我需要做的是让我的代码一次只允许用户输入一个字母和一个符号。下面的示例显示了我希望在更好的视图中看到的内容 目前,我的代码允许用户一次输入多个字符,这是我不想要的 What letter would you like to add? hello What symbol would you like to pair with hello The pairing has been added ['A#', 'M*', 'N', 'HELLOhello'] 我想要的是这样显示一条消息,

好的,我需要做的是让我的代码一次只允许用户输入一个字母和一个符号。下面的示例显示了我希望在更好的视图中看到的内容

目前,我的代码允许用户一次输入多个字符,这是我不想要的

What letter would you like to add?  hello

What symbol would you like to pair with  hello
The pairing has been added
['A#', 'M*', 'N', 'HELLOhello'] 
我想要的是这样显示一条消息,并且不将配对添加到列表中

What letter would you like to add?  hello

What symbol would you like to pair with  hello
You have entered more than one character, the pairing was not added
['A#', 'M*', 'N',].
到目前为止,我在这一部分的代码如下

当用户在字母部分输入一个数字时,打印一条错误消息也是非常好的

def add_pairing(clues):
    addClue = False
    letter=input("What letter would you like to add?  ").upper()
    symbol=input("\nWhat symbol would you like to pair with  ")
    userInput= letter + symbol
    if userInput in clues:
        print("The letter either doesn't exist or has already been entered ")
    elif len(userInput) ==1:
        print("You can only enter one character")
    else:
        newClue = letter + symbol
        addClue = True
    if addClue == True:
        clues.append(newClue)
        print("The pairing has been added")
        print (clues)
    return clues

确保用户输入的最简单方法是使用循环:

while True:
    something = raw_input(prompt)

    if condition: break

像这样设置的东西将继续询问
提示符
,直到满足
条件
。你可以设置
条件
任何你想测试的东西,所以对你来说,它就是
len(某物)!=1

如果允许用户输入字母和符号对,则您的方法可以简化为以下内容:

def add_pairing(clues):
    pairing = input("Please enter your letter and symbol pairs, separated by a space: ")
    clues = pairing.upper().split()
    print('Your pairings are: {}'.format(clues))
    return clues

我喜欢在类似的情况下提出和捕捉异常。对于有“C-ish”背景(Slooow)的人来说,这可能会令人震惊,但在我看来,这是一本完美的pythonic,可读性和灵活性都很强的书

此外,还应添加对预期集合之外的字符的检查:

import string

def read_paring():
    letters = string.ascii_uppercase
    symbols = '*@#$%^&*' # whatever you want to allow

    letter = input("What letter would you like to add?  ").upper()
    if (len(letter) != 1) or (letter not in letters):
        raise ValueError("Only a single letter is allowed")

    msg = "What symbol would you like to pair with '{}'? ".format(letter)
    symbol = input(msg).upper()
    if (len(symbol) != 1) or (symbol not in symbols):
        raise ValueError("Only one of '{}' is allowed".format(symbols))

    return (letter, symbol)

def add_pairing(clues):
    while True:
        try:
            letter, symbol = read_paring()
            new_clue = letter + symbol
            if new_clue in clues:
                raise ValueError("This pairing already exists")
            break # everything is ok 
        except ValueError as err:
            print(err.message)
            print("Try again:")
            continue

    # do whatever you want with letter and symbol
    clues.append(new_clue)
    print(new_clue)
    return clues

不确定要返回什么,但这将检查所有条目:

def add_pairing(clues):
    addClue = False
    while True:
        inp = input("Enter a letter followed by a symbol, separated by a space?  ").upper().split()
        if len(inp) != 2: # make sure we only have two entries
            print ("Incorrect amount of  characters")
            continue
        if not inp[0].isalpha() or len(inp[0]) > 1:  # must be a letter and have a length of 1
            print ("Invalid letter input")
            continue
        if inp[1].isalpha() or inp[1].isdigit(): # must be anything except a digit of a letter
            print ("Invalid character input")
            continue
        userInput = inp[0] + inp[1] # all good add letter to symbol
        if userInput in clues:
            print("The letter either doesn't exist or has already been entered ")
        else:
            newClue = userInput
            addClue = True
        if addClue:
            clues.append(newClue)
            print("The pairing has been added")
            print (clues)               
            return clues

为什么不让用户一起输入字母和配对,用空格分隔?这对你和用户来说都会更容易:
h1b4c3
等等。此外,注释应该给代码添加意义,就像你刚才做的那样添加注释只是分散注意力。我该怎么做,你能为我编辑代码吗?
a,b,c=raw_输入(“输入三个空格分隔的符号”)。split()
@padraic我有点困惑,在代码中哪里添加这个,你能做到吗?不完全确定你想要什么,但是
str.isdigit
将检查字符串是否只包含
数字
为什么要使用
.split(“”)
?你真的不需要将
线索作为参数传递,当您在函数中为其分配一个全新的值时。我不想更改签名,因为我不知道该方法还可以在哪里使用。@Padraic昆宁厄姆显式的旧习惯。我遇到了一个错误,让我给您一个指向我的代码的链接,您也许可以找出原因。。。我使用了raw_input()(python2.x)。很明显,您使用的是python 3.x,因此请检查更新版本(在末尾添加了
input()
return-clues
(尽管如果在内部修改它,返回没有多大意义)。请不要把你的代码发布到某个js编辑器上,没有人会阅读所有的代码。只发布相关部分,若您需要使用外部服务,请使用一些简单的方法,比如pastebinIt。你们的代码在别处肯定有问题,但你们已经有了解决问题的答案。如果你想找人来调试你的所有代码,试试自由职业网站…打印“错误数量的字符”后说无效语法忘记了你在使用python 3,现在可以工作了,测试它,它做的正是它应该做的当我运行代码并转到添加配对选项时,我得到了这个。。。我没有例外,所以你不能从我的代码中得到,你甚至没有运行我的代码我的代码完全按照它应该做的做,它只允许一个字母和任何长度为1的非字母数字字符,所以我看不出它怎么会导致任何错误,你是否实际使用了我的代码,因为回溯不是来自我的函数,这是从另一个答案张贴在这里