-1

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

2 Answers2

0

Also I try to use .join, but now it prints original string, how can I print the string with joined chars?

    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.join(add_character)
    

print("The string after inserting characters: " + str(original_string))
0
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

Yaseen
  • 134
  • 2
  • sorry, forgot to add. the index != 0 is to avoid appending the character at the start of the string – Yaseen Nov 27 '22 at 18:51