简体   繁体   中英

I'm stuck with an list exit error in python

I am a beginner python programmer and I started doing exercises in codewars and Ive got the following assignment:

Complete the solution so that it splits the string into pairs of two characters. If the string contains an odd number of characters then it should replace the missing second character of the final pair with an underscore ('_').

solution('abc') # should return ['ab', 'c_'] solution('abcdef') # should return ['ab', 'cd', 'ef']

now I wrote the following code which gives me the correct result:

def solution(s):
    l = [s[i:i+2] for i in range(0,len(s) ,2)]
    if len(l[-1]) == 1:
        l[-1] += "_"
    return l

print(solution('abc')) -> ['ab', 'c_']
print(solution('asdfadsf')) -> ['as', 'df', 'ad', 'sf']

but when I send submit my code to code wars I get the following error:

if len(l[-1]) == 1: IndexError: list index out of range

an error which I don't get if I test in visual studio code.

can someone please explain to me how can I fix this? thanks:! :)

The problem is l[-1] for an input of '' . In that case your list comprehension returns an empty list [] that has no l[-1] element.

Check empty string input seperately:

def solution(s): 
    if not s: 
        return []

    l = [s[i:i+2] for i in range(0,len(s) ,2)]
    if len(l[-1]) == 1:
        l[-1] += "_"
    return l

print(solution('abc')) # -> ['ab', 'c_']
print(solution('asdfadsf')) # -> ['as', 'df', 'ad', 'sf']

print(solution('')) # -> [] 

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