Reputation: 475
I am trying to create a program that cycles through a string, This is what i have so far.
def main():
name = "firstname lastname"
for i in name:
print(name)
name = name[1::]
main()
This just gives me
firstname lastname
irstname lastname
rstname lastname
stname lastname
tname lastname
and so on till the last letter.
This kind of does what i want but not fully.
What i want this program to do is to print something like this.
firstname lastname
irstname lastname f
rstname lastname fi
stname lastname fir
tname lastname firs
name lastname first
ame lastname firstn
me lastname firstna
and so on....cycling thorugh the string, but i cant quite get it. Any help please.
Thanks in advance
Upvotes: 5
Views: 102
Reputation: 362716
How about using a double ended queue. They have a dedicated rotate method for this kind of thing:
from collections import deque
s = "firstname lastname"
d = deque(s)
for _ in s:
print(''.join(d))
d.rotate()
You can use .rotate(-1)
if you want to spin the other direction.
Upvotes: 3
Reputation: 113988
from itertools import cycle
import time
name = "test string"
my_cool_cycle = [cycle(name[i:]+name[:i]) for i in range(len(name))]
while True:
print "".join(map(next,my_cool_cycle))
time.sleep(1)
just for fun :P
Upvotes: 2
Reputation:
Here's a nifty little one liner that does it too (where x
is the string you want to process):
"\n".join([x[i:]+x[:i] for i in range(len(x))])
Breaking it down:
"\n".join( ... )
- Takes an array and joins the elements with a \n
between each element[ ... for i in ... ]
- Is list comprehension that makes a list by iterating through something elsex[i:]+x[:i]
- Takes the elements from i
and up, and then takes all the elements up to i
and puts them in a new listrange(len(x))
- Makes an iterable of integers from 0
to the length of x
.Upvotes: 0
Reputation: 198
This seems to work. Your array slice doesn't rotate the string, you have to add the first character back to the string, otherwise it gets shorter every iteration through the loop.
Here's a post that explains array slice notation: Explain Python's slice notation
def main():
name = "firstname lastname "
for i in name:
print(name)
#name = name[1::]
name = name[1:] + name[0]
main()
Upvotes: 0
Reputation: 208475
>>> for i in range(len(name)):
... print(name[i:] + " " + name[:i])
...
firstname lastname
irstname lastname f
rstname lastname fi
stname lastname fir
tname lastname firs
name lastname first
ame lastname firstn
me lastname firstna
e lastname firstnam
lastname firstname
lastname firstname
astname firstname l
stname firstname la
tname firstname las
name firstname last
ame firstname lastn
me firstname lastna
e firstname lastnam
Upvotes: 0
Reputation: 170
def main():
name = "firstname lastname"
for i in range(len(name)):
print(name[i:] + name[:i])
main()
Slicing is a wonderful thing. :)
Upvotes: 1