基于字母的对称性创建镜像词

时间:2016-10-26 15:21:04

标签: python string list-comparison

我创建了这个程序,如果它是对称的,它应该显示一个单词的镜像。不幸的是,当我测试“TIMOTHY”时,它表明它无法镜像,我无法弄清楚为什么这不起作用。

#Program for creating a mirrored
#image word#
def main():

    mirrors = ["A","H","I","M","O","T","U","V","W","X","Y"
               "b","d","i","l","m","o","p","t","v","w","x"]

    word = input("Enter in the word you'd like mirrored: ")

    for x in word:
        if x not in mirrors:
            y = True
            break

    if y == True:
        print("Sorry your word can not be mirrored")


    wordlist = ''.join(word[i] for i in range(len(word) -1, -1, -1 ))

    print(wordlist)




main()    

1 个答案:

答案 0 :(得分:5)

mirrors = ["A","H","I","M","O","T","U","V","W","X","Y"
               "b","d","i","l","m","o","p","t","v","w","x"]

这是问题所在。 “b”跟随“Y”而没有任何插入逗号。一个鲜为人知的Python怪癖是两个相邻的字符串文字将自动连接。因此,列表中既不是“Y”也不是“b”,而是“Yb”。

要解决此问题,请添加逗号。

mirrors = ["A","H","I","M","O","T","U","V","W","X","Y",
               "b","d","i","l","m","o","p","t","v","w","x"]

另外,如果您不希望在y = False阻止期间稍后获得UnboundLocalError,则应该在循环之前执行if y == True