Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Cycing through a string

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

like image 654
user1919840 Avatar asked Nov 12 '13 00:11

user1919840


People also ask

How do you loop through a string?

For loops are used when you know you want to visit every character. For loops with strings usually start at 0 and use the string's length() for the ending condition to step through the string character by character. String s = "example"; // loop through the string from 0 to length for(int i=0; i < s.

How do you split a string in a loop in Python?

Example of Splitting Strings into Many Substrings In the below example, you will split the string file into many substrings at line boundaries. Then, you will print out the resulting variable file_split . Finally, complete the for-loop to split the strings into many substrings using commas as a separator element.


2 Answers

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.

like image 177
wim Avatar answered Oct 07 '22 13:10

wim


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

like image 36
Joran Beasley Avatar answered Oct 07 '22 14:10

Joran Beasley