Alice Dee
Alice Dee

Reputation: 21

Python string iterations

What are the logics possible to loop a string into a grid?

For example if I wanted 'water' to print

water
aterw
terwa
erwat
rwate

I was trying something along the lines of,

word = 'water'
for number, letter in enumerate(word):
    if number < len(word):
        print a + word[1:] + word[:1]

I do not comprehend how i can achieve this as you can see from my attempt. Thanks for any help.

Upvotes: 2

Views: 145

Answers (3)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251136

Use collections.deque, it has a rotate method that will do your job.

Rotate the deque n steps to the right. If n is negative, rotate to the left. Rotating one step to the right is equivalent to: d.appendleft(d.pop())

Demo:

from collections import deque
d = deque('water')
for _ in xrange(len(d)):
    print ''.join(d)
    d.rotate(-1)

output:

water
aterw
terwa
erwat
rwate

Upvotes: 4

arghbleargh
arghbleargh

Reputation: 3170

You can do

word = 'water'
for i in xrange(len(word)):
   print word[i:] + word[:i]

Upvotes: 5

Bakuriu
Bakuriu

Reputation: 102029

In [2]: word = 'water'
   ...: for i in range(len(word)):
   ...:     print(word[i:] + word[:i])
water
aterw
terwa
erwat
rwate

The i loops over all possible indexes, takes the suffix starting at that index and prepends it to the string, obtaining all possible rotations.

Upvotes: 5

Related Questions