Home > Software design >  String index out of range, solution is working fine
String index out of range, solution is working fine

Time:09-17

I'm trying to change all the characters to the symbol "#" except the last 4. The error I get:

> Traceback (most recent call last):   
File "tests.py", line 16, in
> <module>
>     r = maskify(cc)   File "/workspace/default/solution.py", line 19, in maskify
>     n[i] = c[i]   IndexError: string index out of range

The code

c = "3656013700"
cc = list(c)
a = (len(cc)-1) - 4
b = []

def maskify(cc):
    n = list(len(cc) * "#")
    while len(cc) <= 4:
        return str(cc)
        break
    else:
        for i in range(len(cc)):
            if i <= a:
                n[i] = n[i]
            else:
                n[i] = c[i]  
    b = "".join([str(i) for i in n])
    return b

maskify(cc)

CodePudding user response:

I don't know why you're complicating it. As @blorgon has already pointed it out, you can directly return it in one line. Further simplifying it, you don't need even need to convert the string into a list. Just directly pass the string as argument.

c = "3656013700"

def maskify(c):
    return (len(c) - 4) * "#"   c[-4:]

print(maskify(c))

If this is not what you're trying to achieve, your question is unclear.

CodePudding user response:

You are going through a complicated route. Here is another approach:

c = "3656013700"
def maskify(cc):
    return cc.replace(cc[:-4], '#'*(len(cc)-4))
print (maskify(c))

Output:

######3700

CodePudding user response:

If you want to go with the iterative approach you can simplify the code substantially:

def maskify(c):
    # Check if lenght of string is 4 or less
    if len(c) <= 4:
        return c

    else:
        # string into a list
        cc = list(c)
        # Iterate over the list - 4 last items
        for i in range(len(c)-4):
            cc[i] = "#"

        return "".join(cc)

s = "3656013700"

s = maskify(s)
print(s)
  • Related