user14665721
user14665721

Reputation:

For loop question is incorrect and I am not sure why

Knowing that strings can be iterated and step every n characters using range(start, stop,n), write a for loop that will get all of the nonoverlapping blocks of three characters from the alphabet string: "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

This is the code that I wrote, but it is wrong. What am I doing wrong.

alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for n in range(0,len(alpha),3):
    print(n,alpha[n])

Upvotes: 0

Views: 60

Answers (2)

Timur Shtatland
Timur Shtatland

Reputation: 12347

Use re.findall like so (note that the last 3-letter word is VWX, and YZ is not printed):

import re
alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
print(re.findall(r'...', alpha))
# ['ABC', 'DEF', 'GHI', 'JKL', 'MNO', 'PQR', 'STU', 'VWX']

Upvotes: 0

Harish Vutukuri
Harish Vutukuri

Reputation: 1150

alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for n in range(0,len(alpha),3):
    print(alpha[n:n+3])

# output
ABC
DEF
GHI
JKL
MNO
PQR
STU
VWX
YZ

Upvotes: 1

Related Questions