Reputation: 9
I have a block of text with the format 'abc,def,ghi,jkl, etc' I need to turn each 3-digit bit into something else, in this case a letter. However, using a for loop, I can't find a way of looking beyond the current character. I'm looking for something a little like this:
for char in message[::4]:
if char == 'a':
if char(+1) == 'b':
newmessage += 1
I'd prefer to use a for loop, but if there's no way of doing it, a while loop would be fine too.
Upvotes: 0
Views: 74
Reputation: 180411
for word in message.split(","):
for ind, char in enumerate(word[:-1], 1):
if char == 'a' and word[ind] == "b":
newmessage += 1
If you want the sum use a generator expression with sum:
new_message = sum(char == 'a' and word[ind] == "b" for word in message.split(",")
for ind, char in enumerate(word[:-1], 1))
Upvotes: 1
Reputation: 3972
for i, char in enumerate(message[::4]):
if char == 'a':
if message[i * 4 + 1] == 'b':
newmessage += 1
Upvotes: 0
Reputation: 4186
Use enumerate
:
for index, char in enumerate(message[::4]):
if char == 'a':
if message[index + 1] == 'b':
newmessage += 1
Upvotes: 0