python中的字典键/值

时间:2016-11-08 00:06:06

标签: python list

我正在尝试构建一个应用程序,该应用程序从用户那里获取输入并对其进行编码并将其显示回用户。用户输入中的每个字母都应该替换为输出中的不同字母。这与字典的键/值一起使用。在我的代码中,它只能使用一个字母,如果输入了更多的字母,那么它就会被打破。任何想法都会非常感激,能够在输入中输入一个单词,并在输出中打印出相反的字母作为单词。

def getInput():

    userInput = input("Enter String to encode: ")
    return userInput

def displayOutput(userInput, encoding ):

    matchFound = False
    for key in encoding:
        if (key == userInput):
            print("Encoded message", encoding[key])
            matchFound = True
            break


    if matchFound == False:
        print("***Error*** No Match Found!")

def main():

    encoding ={"a": "b", "b": "c", "c": "d", "d": "e", "e": "f", "f": "g", "g": "h", "h": "i", "i": "j", "j": "k", "k": "l", "l": "m", "m": "n", "n": "o", "o": "p", "p": "q", "q": "r", "r": "s", "s": "t", "t": "u", "u": "v", "v": "w", "w": "x", "x": "y", "y": "z", "z": "a", " ": "-"}


    userInput = getInput()
    displayOutput(userInput, encoding)


main()

3 个答案:

答案 0 :(得分:0)

您正在将编码元素与整个userInput进行比较;你需要单独处理它的每个字符。

答案 1 :(得分:0)

您应该迭代userInput字符串中的字符,而不是将整个输入字符串与编码键进行比较。类似的东西:

encodedString = ""

for inputChar in userInput:
    if ( inputChar in encoding ):
        encodedChar = encoding[inputChar]
        encodedString = encodedString + encoding[inputChar]
    else:
        encodedString = encodedString + inputChar

(未经测试......只是在我的头顶打字,所以实际上可能无法运行。)

此解决方案假设您需要输出字符串(encodedString),而对于不在编码中的字符,您只需使用输入字符。不确定这是不是你真正想要的。

编辑:如果您希望它仅适用于编码中的输入字符,则mrdomoboto的解决方案更高效,更紧凑。

答案 2 :(得分:0)

如果我理解您的要求,以下方法可能对您有用。尝试编码,如果没有值条目,则处理找不到现有编码的情况。

def encode(s, encoding):
    try:
        return ''.join(encoding[character] for character in s)
    except KeyError:
        print "Encoding not found."

示例输出:

>>> encoding = {"a": "b", "b": "c", "c": "d", "d": "e", "e": "f", "f": "g", "g": "h", "h": "i", "i": "j", "j": "k", "k": "l", "l": "m", "m": "n", "n": "o", "o": "p", "p": "q", "q": "r", "r": "s", "s": "t", "t": "u", "u": "v", "v": "w", "w": "x", "x": "y", "y": "z", "z": "a", " ": "-"}
>>> encode("helloworld", encoding)    
ifmmpxpsme
>>> encode("HelloWorld", encoding) 
Encoding not found.   
相关问题