Search code examples
pythonstringinsert

How to insert every nth charts in string? PYTHON


I have a code, but I don't really know python, so I have a problem. I know that the insert isn't right for strings but I don't know how can I insert?

original_string = input("What's yout sentence?")
add_character = input("What char do you want to add?")
slice = int(input("What's the step?"))

for i in original_string[::slice]:
    original_string.insert(add_character)

print("The string after inserting characters: " + str(original_string))

So I need help, how can I rewrite this? That's the homework for university and we haven't studied def so I can't use it


Solution

  • original_string = input("What's yout sentence?")
    add_character = input("What char do you want to add?")
    slice = int(input("What's the step?"))
    
    new_string = ""
    
    for index, letter in enumerate(original_string):
        if index % slice == 0 and index != 0:
            new_string += add_character + letter
        else:
            new_string += letter
    
    print("The string after inserting characters: " + str(new_string))
    

    Explanation: Strings are immutable so we'll have to create a new string to append to. So loop through the original string, take each letter and its index. If the index is a multiple of the slice, then add the character in add_character variable along with the letter, otherwise only append the letter. This will add the character at every multiple of the slice. I believe this is what the code was trying to achieve atleast, correct me if I'm wrong