2014-03-13 87 views
0

我試圖使用一個for循環週期在一個字符串打印出來是這樣的:循環通過字符串使用for循環

 s u p e r n a t u r a l 
    u p e r n a t u r a l s 
    p e r n a t u r a l s u 

這裏是我到目前爲止的代碼:

def main(): 
     first_Name = "s u p e r n a t u r a l" 
     print(first_Name) 
     for i in range(len(first_Name)): 
      print(first_Name[i]) 


main() 
+0

如果您不需要多次循環長字符串,那麼只需複製像'HelloHelloHello'這樣的字符串並使用一個for循環打印出來呢? – shole

+0

可能重複的[字符串中的字符的python循環移位](http://stackoverflow.com/questions/10826253/python-cyclic-shifting-of-the-characters-in-the-string) – gongzhitaao

+0

你是通過預先插入額外的空間實際上使其變得更加困難 –

回答

0
In [11]: 

S='s u p e r n a t u r a l' 
SL=S.split(' ') 
for i in range(len(S)-S.count(' ')): 
    print ' '.join(SL[i:]+SL[:i]) 
s u p e r n a t u r a l 
u p e r n a t u r a l s 
p e r n a t u r a l s u 
e r n a t u r a l s u p 
r n a t u r a l s u p e 
n a t u r a l s u p e r 
a t u r a l s u p e r n 
t u r a l s u p e r n a 
u r a l s u p e r n a t 
r a l s u p e r n a t u 
a l s u p e r n a t u r 
l s u p e r n a t u r a 
0

真是巧合,在我的諮詢工作中,我做了同樣的事情!但嚴重的是,讓你開始你的功課,這裏有一些想法:

>>> print first_Name[0:] + ' ' + first_Name[:0] 
s u p e r n a t u r a l 
>>> print first_Name[1:] + ' ' + first_Name[:1] 
u p e r n a t u r a l s 
>>> print first_Name[2:] + ' ' + first_Name[:2] 
u p e r n a t u r a l s 

看起來有前途,至少偶數...

如何只通過偶數迭代?

>>> help(range) 

step是你的朋友在這裏。

>>> range(0, len(first_Name), 2) 
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22] 

我打賭你可以(也應該)弄清楚其餘的。

0

這樣做的一個簡單的方法:

#!/usr/bin/env python 

def rshift(s, i): 
    i = i % len(s) 
    return s[-i:] + s[0:-i] 

if __name__ == '__main__': 
    s = "12345" 
    for i in range(len(s)): 
     print rshift(s, -i) 
0

對我來說,這是一個雙端隊列取得

import collections 
d = collections.deque('supernatural') 
for _ in range(len(d)): 
    print(' '.join(d)) 
    d.rotate(-1) 

打印出:

s u p e r n a t u r a l 
u p e r n a t u r a l s 
p e r n a t u r a l s u 
e r n a t u r a l s u p 
r n a t u r a l s u p e 
n a t u r a l s u p e r 
a t u r a l s u p e r n 
t u r a l s u p e r n a 
u r a l s u p e r n a t 
r a l s u p e r n a t u 
a l s u p e r n a t u r 
l s u p e r n a t u r a 
1

我有它在4線:

li = list('supernatural') 
for c in li: 
    print ''.join(li) 
    li.append(li.pop(0))