Domanda

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

È stato utile?

Soluzione 3

def main():
    name = "firstname lastname"

    for i in range(len(name)):
        print(name[i:] + name[:i])
main()

Slicing is a wonderful thing. :)

Altri suggerimenti

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.

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

>>> 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

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()

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 else
  • x[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 list
  • range(len(x)) - Makes an iterable of integers from 0 to the length of x.
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top