-5

假设我有一个字符串,例如:

Hello world

我想迭代每个字符,以便迭代打印:

H
He
Hel
Hell
Hello
Hello(space) 
Helllo W... etc

怎么可能做到这一点?

4

1 回答 1

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
>>>
于 2013-10-18T15:50:36.137 回答