python - 如何暂时忽略标点符号? Python

标签 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)

但是如果用户输入像“0001,0001”这样的消息,我希望结果是“1,1”。我怎样才能让我的代码暂时忽略标点符号,这样它就不会弄乱我的代码中的索引+4,并且稍后仍然能够打印出标点符号?

最佳答案

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

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) 在最后。只是为了性能目的。

关于python - 如何暂时忽略标点符号? Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23726645/

相关文章:

Python 套接字监听

python - Google App Engine queue.yaml 在开发服务器中不工作

python - 如何使 cython 函数接受 float 或 double 数组输入?

python Pandas : Get rows where previous values are greater than 0

python - odoo onchange 没有得到数据

python - 谁能给我解释一下 "guardian pattern"

python - Cox 回归 python

用于参数化 CAD 的 Python 模块

python - groupby 和过滤 Pandas

Python 表格格式 : want to display the table with one blank element