假设我有一个字符串,如:
Hello world
我想迭代每个字符,以便打印迭代:
H
He
Hel
Hell
Hello
Hello(space)
Helllo W... etc
怎么可以这样做?
答案 0 :(得分:2)
只需切片:
>>> mystr = 'Hello world'
>>> for i in range(len(mystr)+1):
... print mystr[:i]
...
H
He
Hel
Hell
Hello
Hello
Hello w
Hello wo
Hello wor
Hello worl
Hello world
>>>
或者,一线解决方案:
>>> # This might be slower though if the string is massive
>>> print "\n".join([mystr[:i] for i in range(len(mystr)+1)])
H
He
Hel
Hell
Hello
Hello
Hello w
Hello wo
Hello wor
Hello worl
Hello world
>>>