Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用for循环循环遍历字符串_Python_String_Loops - Fatal编程技术网

Python 使用for循环循环遍历字符串

Python 使用for循环循环遍历字符串,python,string,loops,Python,String,Loops,我尝试使用单个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_Na

我尝试使用单个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()

真是巧合,我在咨询工作的早些时候也在做同样的事情!但说真的,为了让你开始做作业,这里有一些想法:

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

我打赌你能(也应该)解决剩下的问题。

一个简单的方法:

#!/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)

对我来说,这是为一个女人做的

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
我有四行:

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

如果你不需要在一个长字符串上循环多次,那么只需像“HelloHelloHello”一样复制该字符串,并使用单个for循环将其打印出来怎么样?可能的重复实际上是通过预插入额外的空格使其更加困难
li = list('supernatural')
for c in li:
    print ''.join(li)
    li.append(li.pop(0))