pythonstringappend

Python - How to insert '*' into a string after every nth character


I'm currently stuck on this question that takes 2 arguments (string, and an int, n) and it should return a new string where every nth character (from 0) is followed by an '*'.

I've found similar questions on stack overflow but the answers include more advanced coding functions that I don't know how to use (like range(), emurate etc) as I just started out coding.

What the code supposed to do:

>>> string_chunks("Once upon a time, in a land far, far away", 5)
'O*nce u*pon a* time*, in *a lan*d far*, far* away*'

My code so far only prints out every 5th character from the string:

def string_chunks(string, x):
    new = ''
    for ch in string[::x]:
        new += ch 
    return new

>>>'Ouae nrry'

I'm not sure if I'm supposed to use str.find()/str.split() in my code. It would be a great help if someone can help me improve or guide me. Thanks!


Solution

  • Your example seems incorrecnt. nth position meaning each index is a multiple of n.

    But, if your phrasing is wrong, you can always shift n or cnt to make sure it matches your desired output.

    You are not adding any starts in your function, just check if the position is a multiple of x, if yes then add a *.

    def string_chunks(string, x):
        new = ''
        cnt = 0
        for ch in string:
            if cnt%x==0 and cnt!=0: # checking if cnt is a multiple of x and not 0, we don't want to put star at index 0
                new += '*'
            cnt += 1
            new += ch
        return new
    string_chunks("Once upon a time, in a land far, far away", 5)
    

    Out: 'Once *upon *a tim*e, in* a la*nd fa*r, fa*r awa*y'