Say I have string:
string = 'ABCDEFGHI'
and I want to iterate over the string so the output will be:
ABC
DEF
GHI
Is this feasible? Can I just do something along the lines of:
for i in string, 3:
print i
I feel like there is an easier solution that I am missing.
A simple for
loop to accomplish this would be:
for i in range(3, len(string) + 1, 3):
print string[i-3:i]
Which uses a step=3
value for range()
to iterate by 3's
and then, utilizing a slice
object which depends on the value of i
you get the resulted sliced string. For string = 'ABCDEFGHI'
this prints:
ABC
DEF
GHI
And of course you can remove the hardcoded 3
with a variable, say gap = 3
to make the loop more visually pleasing:
gap = 3
for i in range(gap, len(string) + 1, gap):
print string[i-gap: i]
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