Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading