遍历一个字符串,直到确切的值在字典中

iterate through a string until the exact value is in the dictionary

我正在尝试使用包含这些键和值的字典来解码二进制字符串

数据=“1001011101100100001000100000010011000000000100”

sdict = {"100":"h", "101":"e", "110":"l", "0100":"o","00100":"w","0000100 ":"r","00000000100":"d"}

这是我目前尝试过的方法:

for i in range(len(data)):
if data[i] in sdict.keys():
    decoded += sdict[data[i]]
else:
    decoded += data[i]

It gives me this error

解码后的消息应该是 helloworld

您的代码存在的问题是您将每个字符与多个字符的字符串进行比较。这就是我下面示例中 history 变量的用途。它收集每个字符,直到达到完整字符串与字典中的键匹配的点。

你可以试试这个:

decoded = ""   
history = ""  # all characters visited since last key was found
for i in data:
    history += i                     #  add each character to history
    if history in sdict:             # if history is a key in dictionary
        decoded += sdict[history]    # add key's value to decoded
        history = ""                 # reset history

输出=helloworld