Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over every nth element in string in loop - python

How can iterate over every second element in string ?

One way to do this would be(If I want to iterate over nth 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 thery any "pythonic" way to do this? (I am pretty sure my method is not good)

like image 914
Agile_Eagle Avatar asked Jul 01 '18 09:07

Agile_Eagle


People also ask

How do you iterate over a string of elements?

One way to iterate over a string is to use for i in range(len(str)): . In this loop, the variable i receives the index so that each character can be accessed using str[i] .

Can you iterate over a string Python?

You can traverse a string as a substring by using the Python slice operator ([]). It cuts off a substring from the original string and thus allows to iterate over it partially. To use this method, provide the starting and ending indices along with a step value and then traverse the string.

How do you iterate through a range in a list?

We can iterate through a list by using the range() function and passing the length of the list. It will return the index from 0 till the end of the list. The output would be the same as above.


1 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
like image 145
Druta Ruslan Avatar answered Sep 20 '22 15:09

Druta Ruslan