Iterate over every nth element in string in loop – python

Question:

How can iterate over every second element in string ?

One way to do this would be (if I want to iterate over every n-th element):

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

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

Asked By: Agile_Eagle

||

Answers:

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
Answered By: Druta Ruslan

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

Try using slice:

sample = "This is a string"
for i in sample[slice(None,None,2)]:
   print(i)

Output:

T
i

s
a
s
r
n
Answered By: U12-Forward

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
Answered By: user3668741
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.