1

i am trying to iterate though a string and check if the consecutive characters are the same. If not i want to inset a space between them. Then store this new string in the Mynewstring until the while loop goes through all characters.

I am posting a While loop, a tried this also with a For loop, to the same result. Any help will be appreciated!

mystr = '77445533'
mynewstring = ""

myind = 0

while myind < len(mystr)+1:
  if mystr[myind] != mystr[myind +1]:
    mynewstring = mystr[:(myind)] + " " + mystr[(myind+1):]
  myind+=1

print(mynewstring)

1 Answer 1

1

Instead of indexes you could use an iterator. I used the zip function to iterate through characters starting from the beginning and from the first character. If the characters were different then a space is inserted.

The only special case was to add the last character which wouldn't be matched with anything since the first iterator would be finished.

mystr = '77445533'
mynewstring = ''

for pair in zip(mystr, mystr[1:]):
    mynewstring += pair[0]
    if pair[0] != pair[1]:
        mynewstring += ' '
mynewstring += mystr[-1]
Sign up to request clarification or add additional context in comments.

2 Comments

This one is good, but i thinkg it would work only if there are 2 instances of each character? What if for example there is one more 7 at the start?
Have you tried it out at all? The only point a space will be appended is if the two characters its comparing are different. Otherwise, it's appending just the next character.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.