-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

3
  • stackoverflow.com/questions/4022827/… This will be helpful I think Commented Nov 27, 2022 at 18:39
  • Could you please post an example of the input and the expected output? Commented Nov 27, 2022 at 18:42
  • Hi, to me the easiest way would be like this .. original_string = original_string[:slice] + add_character + original_string[slice:] Commented Nov 27, 2022 at 19:12

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.