在 python 我试图解析一个字符串,其中元素和索引加上一个 returns 所需的索引

In python Im trying to parse a string where the element and the index plus one returns the desired index

她的是我的代码挑战和我的代码。我卡住了,不知道为什么它不能正常工作

-编写一个名为 plaintext 的函数,该函数采用以这种格式编码的字符串的单个参数:在消息的每个字符之前,添加一个数字和一系列其他字符。该数字应与消息实际有意义的字符之前的字符数相对应。它应该return字符串形式的解码词

"""  my pseudocode:
    #convert string to a list
    #enumerate list
    #parse string where the element and the index plus one returns the desired index
    #return decoded message of desired indexes  """

encoded_message = "0h2ake1zy"
#encoded_message ="2xwz"
#encoded_message = "0u2zyi2467"

def plaintext(string):
    while(True):
        #encoded_message = raw_input("enter encoded message:")
        for index, character in enumerate(list(encoded_message)):
            character = int(character)
            decoded_msg = index + character + 1
        print decoded_msg

您需要遍历字符串的字符,并在每次迭代中跳过指定数量的字符并获取以下字符:

def plaintext(s):
    res = ''
    i = 0
    while i < len(s):
        # Skip the number of chars specified
        i += int(s[i])

        # Take the letter after them
        i += 1
        res += s[i]

        # Move on to the next position
        i += 1

    return res

这里有一些提示。

首先决定要使用哪种循环结构。 Python 提供选择:迭代单个字符、循环字符的索引、while 循环。您当然不希望同时使用 while 和 for 循环。

您将按组处理字符串,“0h”,然后是“2ake”,然后是“1zy”以获取您的第一个示例字符串。退出循环的条件是什么?

现在,看看你的行 decoded_msg = index + character + 1。要构造解码后的字符串,您需要根据数字的值对字符串本身进行索引。所以,这一行应该包含类似 encoded_message[x] for some x 的内容,你必须使用数字来计算。

另外,你会想在游戏过程中积累角色。因此,您需要以空结果字符串 decoded_msg="" 开始循环,并在循环的每次迭代中向其添加一个字符 decoded_msg += ...

我希望这不仅仅是给出答案,还能有所帮助。