Home > Software engineering >  why i getting IndexError: list index out of range
why i getting IndexError: list index out of range

Time:12-03

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 ('_').

Examples:

  • 'abc' => ['ab', 'c_']
  • 'abcdef' => ['ab', 'cd', 'ef']

https://prnt.sc/E2sdtceLtkmF



# **My Code:**

def solution(s):
    ```n = 2
    ```sp = [s[index : index   n] for index in range(0, len(s), n)]
    
    ```if len(sp[-1]) == 1:
        sp[-1] = sp[-1]   "_"
        ```return sp
    ```else:
        ```return sp
    
        

and i geting this error:

Traceback (most recent call last):
  File "/workspace/default/tests.py", line 13, in <module>
    test.assert_equals(solution(inp), exp)
  File "/workspace/default/solution.py", line 5, in solution
    if len(sp[-1]) == 1:
IndexError: list index out of range

# pls someone help

CodePudding user response:

You need to test for the possibility that the input parameter is an empty string.

def solution(s):
    n = 2
    sp = [s[index : index   n] for index in range(0, len(s), n)]
    if sp and len(sp[-1]) == 1:
        sp[-1]  = '_'
    return sp

CodePudding user response:

its fixed by adding another if len(sp) = 0: return sp

def solution(s):
    n = 2
    sp = [s[index : index   n] for index in range(0, len(s), n)]

    if len(sp) == 0:
       return sp

    if len(sp[-1]) == 1:
       sp[-1] = sp[-1]   "_"
       return sp

    else:
       return sp
  • Related