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)
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] .
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With