如何从代码中排除非字母字符?

时间:2014-08-28 01:05:46

标签: python

#when I run it, it says something about a function discrimination being at 0x0E....

import string
import sys

code = raw_input("Enter your code: ")

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

lettered_code = list(code)

def translate(lettered_code):
    newanswer = ""
    for letters in lettered_code:
        newanswer += translation[letters]
    return newanswer

def checking(translate):
    return all((char in string.letters) for char in translate)

def discrimination(translate):
    if checking == False:
        print "Only letters!"
    else: 
        print translate(lettered_code)
    sys.exit()

print discrimination

2 个答案:

答案 0 :(得分:1)

您可以使用isalpha方法检查它是否为字母

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

s = 'this is a test 123 that has numbers456 in the wr48ds'
newS = ''
for letter in s:
    if letter.isalpha():
        newS += translation[letter]
    else:
        newS += letter

>>> newS
'wklv lv d whvw 123 wkdw kdv qxpehuv456 lq wkh zu48gv'

答案 1 :(得分:0)

您的print discrimination正在打印功能对象!

你不应该将翻译称为歧视变量......就像这样:

def discrimination():
    if checking == False:
        print "Only letters!"
    else: 
        print translate(lettered_code)
    sys.exit()


discrimination()  # don't need the print statement here either

但这只会让你到目前为止......只要你输入字母就行了...... 你应该考虑重做所有这些功能。