Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating Over a String in Threes

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.

like image 400
Sean Avatar asked Oct 19 '25 11:10

Sean


1 Answers

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] 
like image 109
Dimitris Fasarakis Hilliard Avatar answered Oct 21 '25 03:10

Dimitris Fasarakis Hilliard