M_Delineshev
M_Delineshev

Reputation: 115

Iterate through a string and slice it - index error - Python

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)

Upvotes: 1

Views: 52

Answers (1)

DarkArctic
DarkArctic

Reputation: 96

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]

Upvotes: 1

Related Questions