Search code examples
pythonstringloopsiteration

How can I iterate over every nth element in a string in a loop?


Is there any "pythonic" way to do this? I am pretty sure my method is not good:

sample = "This is a string"
n = 3 # I want to iterate over every third element
i = 1
for x in sample:
    if i % n == 0:
        # do something with x
    else:
        # do something else with x
    i += 1

Solution

  • If you want to do something every nth step, and something else for other cases, you could use enumerate to get the index, and use modulus:

    sample = "This is a string"
    n = 3 # I want to iterate over every third element
    for i,x in enumerate(sample):
        if i % n == 0:
            print("do something with x "+x)
        else:
            print("do something else with x "+x)
    

    Note that it doesn't start at 1 but 0. Add an offset to i if you want something else.

    To iterate on every nth element only, the best way is to use itertools.islice to avoid creating a "hard" string just to iterate on it:

    import itertools
    for s in itertools.islice(sample,None,None,n):
        print(s)
    

    result:

    T
    s
    s
    
    r
    g