擅长:python、mysql、java
<p>最简单的是:</p>
<pre><code>>>> def print_reversed(s):
... for letter in reversed(s):
... print letter,
...
>>> print_reversed('banana')
a n a n a b
>>>
</code></pre>
<p>其他可能的解决方案是将索引作为字符串的最后一个索引。然后,您将逐字反向读取字符串,每次将索引值降低1。然后你展示的代码片段会变成:</p>
<pre><code>>>> def print_reversed2(s):
... index = len(s) - 1
... while index >= 0:
... letter = fruit[index]
... print letter
... index = index - 1
...
>>> print_reversed2('banana')
a
n
a
n
a
b
>>>
</code></pre>
<p>使用交互式解释器(只需在命令提示符中键入“python”)可以帮助您尝试使用这种代码snipplet。例如:</p>
<pre><code>>>> fruit = 'banana'
>>> len(fruit)
6
>>> len(fruit) - 1
5
>>> while index >= 0:
... print "index at: " + str(index)
... print "fruit[index] at: " + fruit[index]
... index = index - 1
...
index at: 5
fruit[index] at: a
index at: 4
fruit[index] at: n
index at: 3
fruit[index] at: a
index at: 2
fruit[index] at: n
index at: 1
fruit[index] at: a
index at: 0
fruit[index] at: b
>>>
</code></pre>