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

4

14

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
Helenahelene answered 1/7, 2018 at 9:9 Comment(1)
for i,x in enumerate(sample,1):Palermo
N
14

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
Neap answered 1/7, 2018 at 9:16 Comment(3)
This is the most comprehensive answerHelenahelene
islice is a lot slower than just using a regular slice, since it has to actually retrieve every character from the string and ignore the ones it's not interested in, while a regular slice can skip straight to the elements it needs.Phlebosclerosis
probably a trade-off between creating a string with s[::n] (memory copy but fast iteration). If the string is big, maybe islice is better but you're probably right for regular-sized strings.Palermo
A
21

you can use step for example sample[start:stop:step]

If you want to iterate over every second element you can do :

sample = "This is a string"

for x in sample[::2]:
    print(x)

output

T
i

s
a
s
r
n
Ankylose answered 1/7, 2018 at 9:10 Comment(2)
it doesn't answer to "do something every even item and do something else every odd item" though.Palermo
@Jean-FrançoisFabre Yes but still it is useful and partly answers my questionHelenahelene
N
14

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
Neap answered 1/7, 2018 at 9:16 Comment(3)
This is the most comprehensive answerHelenahelene
islice is a lot slower than just using a regular slice, since it has to actually retrieve every character from the string and ignore the ones it's not interested in, while a regular slice can skip straight to the elements it needs.Phlebosclerosis
probably a trade-off between creating a string with s[::n] (memory copy but fast iteration). If the string is big, maybe islice is better but you're probably right for regular-sized strings.Palermo
A
1

Logic to print every nth character:

#Sample input = 'abcdefghijkl'
#n = 4
for i in range(0,4):
    for x in input[i::4]:
        print(x, end='')

Output:

aeibfjcgkdhl
Ardellardella answered 23/9, 2021 at 11:20 Comment(0)
B
0

Seeing the answers above - except the mostly voted one (which doesn't fully cover the request) - it was mainly division in a loop. Why not keep it more "programmatic", even if yet not that pythonic? Here is example based on original question (no division used):

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

If you sill like to process with valid index:

sample = "This is a string"
n = 3 # I want to iterate over every third element
# (!) here do something else with all elements within list/substring: sample[0:n-1]
for i in range(n-1, len(sample), n):
    # (!) here do something with element: sample[i]
    # (!) here do something else with all elements within list/substring: sample[i+1:i+n]

And now coming back to solution with division, but as a single line:

sample = "This is a string"
n = 3 # I want to iterate over every third element
# you can call below your own correspondent functions (according to case) instead of print() ;-)
_ = [print('Do something: ' + sample[i]) if 0 == ((1+i) % n) else print('Do something else: ' + sample[i]) for i in range(len(sample))]
Bulbar answered 16/7, 2024 at 13:18 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.