[英]How to temporarily ignore punctuation? python
hi i'm trying to write a function to decode a message the user entered 嗨,我正在尝试编写一个函数来解码用户输入的消息
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)
but if the user input a message like "0001,0001", which i would like the result be "1,1". 但是如果用户输入的消息是“ 0001,0001”,我希望结果是“ 1,1”。 How could i make my code temporarily ignore punctuation so it doesn't mess up with my indexing +4 in my code and still able to print out the punctuation later?
我该如何使我的代码暂时忽略标点符号,以便它不会与我的代码中的索引+4混淆,并在以后仍能打印出标点符号?
You can check if the next characeter is an integer. 您可以检查下一个字符是否为整数。 If not, just add it to the string and continue to the next character:
如果没有,只需将其添加到字符串中,然后继续下一个字符:
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
Here is an example of execution: 这是执行示例:
>>> def decode(cypher, msg):
... # ...
>>> decode(decypherbook, '0001,0010')
'1,0'
Side note: You could also prefer to make a list as a buffer instead of recreating a string every time (string are immutable, every +=
creates a new object) and do ''.join(buffer)
at the end. 旁注:您也可以将列表作为缓冲区而不是每次都重新创建字符串(字符串是不可变的,每个
+=
创建一个新对象),然后在末尾执行''.join(buffer)
。 Just for performance purpose. 仅出于性能目的。
Use split method from string object 使用字符串对象的拆分方法
userdecode = raw_input("Enter the number you want to de-cypher: ")
userdecode_list = userdecode.split(",")
And than call your function like this with join method from string object 而且比从字符串对象使用join方法调用这样的函数
print "After de-cypher: ", decode(decypherbook, "".join(userdecode_list))
I feel like replace
matches your need more. 我觉得
replace
更符合您的需求。
def decode(cypher, msg):
for key, value in cypher.items():
msg = msg.replace(key, str(value))
return msg
A fun-one-liner (which assumes userdecode
is guaranteed to be of the form r"(\\d{4},)*"
) 一个有趣的代码(假设
userdecode
的格式一定为r"(\\d{4},)*"
)
def decode(cypher, msg):
return ",".join([str(cypher[x]), for x in userdecode.split(",")])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.