gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 05:13:20 24 4
gpt4 key购买 nike

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com