Home > Net >  Skipping iterations in a for loop when working with strings (in Python)
Skipping iterations in a for loop when working with strings (in Python)

Time:10-25

I'm trying to write a program that works with a string as input (a sentence or word). With a for loop, I iterate through each character in turn. When I come across the letter p, the program should skip a couple of iterations. I have found a lot of tips regarding skipping iterations when working with integers. However, in my code, I'm working with strings. Does anyone have any helpful tips for this? Thanks in advance!

Here is an adapted piece of my code (what I have so far):

language_input = input()

for character in language_input:

    if character == "p":
        # Now, I have to skip a few iterations (e.g. skip 3 characters)

CodePudding user response:

You can use an extra variable and do nothing if it is set

language_input = input()
check = 0
for character in language_input:
    if check:
        check -= 1
        continue

    if character == "p":
        check = 3 #set to number of iterations you want to skip

CodePudding user response:

It rather depends on what you need to do with the characters in your string. Here's an idea:

language_input = input()
i = 0
while i < len(language_input):
    if language_input[i] == 'p':
        i  = 3
    else:
        i  = 1
        # do something else

CodePudding user response:

You could use an iterator:

language_input = 'abcdefghij'
s = iter(language_input)
while True:
    try:
        character = next(s)
        if character == 'd':
            print('…', end='')
            next(s)
            next(s)
            next(s)
        print(character, end='')
    except StopIteration:
        break

output: abc…dhij

To be more efficient in skipping many items, you could use itertools.islice:

from itertools import islice

# … only showing changed part of code
if character == 'd':
    print('…', end='')
    list(islice(s, 3)) # get 3 elements at once
# …
  • Related