简体   繁体   中英

how to fix ValueError: list index out of range

I keep getting this error:

line 23, in encode raw_out[i][pos] = message[pos] IndexError: list index out of range

for this part of the program:

def encode(message: str, key: int) -> str:
"""
Encode text using Rail-fence Cipher.

Replace all spaces with '_'.

:param message: Text to be encoded.
:param key: Encryption key.
:return: Decoded string.
"""
message = message.replace(" ", "_")

down = True
raw_out = []
out = ''
i = 0
for x in range(key):
    raw_out.append({})
for pos in range(len(message)):
    raw_out[i][pos] = message[pos]
    if i == key - 1:
        down = False
    if i == 0:
        down = True
    if down:
        i = i + 1
    else:
        i = i - 1
for p in raw_out:
    for q in p:
        out += p[q]
return out

I'm not sure how to fix the error. Any ideas?

When key is one or when the key is bigger than the length of the string return the string as it is. Doesn't make sense to do any processing.

right after the line

message = message.replace(" ", "_")

you can check for the condition

if key == 1 or key > len(message):
    return message

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM