如何暂时忽略标点符号?蟒蛇

时间:2014-05-18 20:41:42

标签: python python-2.7

您好我正在尝试编写一个函数来解码用户输入的消息

decypherbook = {'0000':8, '0001':1, '0010':0, '0011':9, '0100':5, '0101':3, '0110':7, '0111':2, '1110':4, '1111':6} 
userdecode = raw_input("Enter the number you want to de-cypher: ")
def decode(cypher, msg):
    length = len(msg)
    decoded = ""
    key_index = 0 ## starting position of a key in message
    while key_index < length: 
        key = msg[key_index:key_index + 4]
        decoded += str(cypher[key])
        key_index += 4
    return decoded

print "After de-cypher: ", decode(decypherbook, userdecode)

但是如果用户输入了像&#34; 0001,0001&#34;这样的消息,我希望结果为&#34; 1,1&#34;。我怎么能让我的代码暂时忽略标点符号所以它不会搞砸我的代码中的索引+4,并且仍然可以在以后打印出标点符号?

4 个答案:

答案 0 :(得分:2)

您可以检查下一个characeter是否为整数。如果没有,只需将其添加到字符串并继续下一个字符:

def decode(cypher, msg):
    length = len(msg)
    decoded = ""
    key_index = 0 ## starting position of a key in message
    while key_index < length: 
        key = msg[key_index:key_index + 4]
        decoded += str(cypher[key])
        key_index += 4

        # Pass every non digit after
        while key_index < length and not msg[key_index].isdigit():
             decoded += msg[key_index]
             key_index += 1

    return decoded

以下是执行的示例:

>>> def decode(cypher, msg):
... # ...
>>> decode(decypherbook, '0001,0010')
'1,0'

旁注:你也可以选择将列表作为缓冲区而不是每次都重新创建一个字符串(字符串是不可变的,每个+=创建一个新对象)并在最后执行''.join(buffer) 。仅出于性能目的。

答案 1 :(得分:0)

使用字符串对象的分割方法

userdecode = raw_input("Enter the number you want to de-cypher: ")
userdecode_list = userdecode.split(",")

然后用字符串对象

中的join方法调用你的函数
print "After de-cypher: ", decode(decypherbook, "".join(userdecode_list))

答案 2 :(得分:0)

我觉得replace符合您的需求。

def decode(cypher, msg):
    for key, value in cypher.items():
        msg = msg.replace(key, str(value))

    return msg

答案 3 :(得分:0)

一个有趣的单行(假定userdecode保证为r"(\d{4},)*"

def decode(cypher, msg):
    return ",".join([str(cypher[x]), for x in userdecode.split(",")])