如何暂时忽略标点符号?python
嗨,我正在尝试编写一个函数来解码用户输入的消息如何暂时忽略标点符号?python,python,python-2.7,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(
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)
decypherbook={'0000':8,'0001':1,'0010':0,'0011':9,'0100':5,'0101':3,'0110':7,'0111':2,'1110':4,'1111':6}
userdecode=raw_input(“输入要破译密码的数字:”)
def解码(密码、消息):
长度=长度(msg)
decoded=“”
key_index=0##消息中某个键的起始位置
而键索引<长度:
key=msg[键索引:键索引+4]
解码+=str(密码[键])
键索引+=4
返回解码
打印“反密码后:”,解码(decypherbook,userdecode)
但是如果用户输入一条像“0000001”这样的消息,我希望结果是“1,1”。如何使代码暂时忽略标点符号,这样它就不会干扰代码中的索引+4,并且以后仍然能够打印标点符号?使用string对象的split方法
userdecode = raw_input("Enter the number you want to de-cypher: ")
userdecode_list = userdecode.split(",")
print "After de-cypher: ", decode(decypherbook, "".join(userdecode_list))
然后使用string对象中的join方法像这样调用函数
userdecode = raw_input("Enter the number you want to de-cypher: ")
userdecode_list = userdecode.split(",")
print "After de-cypher: ", decode(decypherbook, "".join(userdecode_list))
您可以检查下一个字符是否为整数。如果没有,只需将其添加到字符串并继续下一个字符:
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
旁注:您也可以选择创建一个列表作为缓冲区,而不是每次(字符串是不可变的,每个
+=
创建一个新对象)都重新创建一个字符串,并在末尾执行''。加入(缓冲区)
。只是为了性能目的 我觉得replace
更符合您的需要
def decode(cypher, msg):
for key, value in cypher.items():
msg = msg.replace(key, str(value))
return msg
有趣的单行程序(假定userdecode
的形式保证为r”(\d{4},)*“
)
如果用户输入“00010001”,则“索引混乱”,因此结果将为“1”。有没有一种方法可以忽略“,”因为密码键是每4个索引,但不是完全删除“,”我们暂时忽略它,所以结果是“11”,然后在程序结束时将其放回,结果变成“1,1”这就是我用修正后的算法所做的:我跳过了4个字符组之间的每一个非数字字符。它不起作用吗?我用你的代码试过了,但结果显示为“1”,如此接近,我看不出它在哪里wrong@user3620442我已经更正了我的代码,并发布了一个示例(对我来说很有用)哇,更改键索引<长度位置如何改变结果?无论如何,非常感谢您,我不知道您希望它有多强大,但您应该知道,在一些国家,他们使用
分隔千,使用,
分隔小数。