Python - 编写一个函数,接收字符串参数并逐行反向输出字母
这是一本名为《如何像计算机科学家一样思考》的书中的一个练习。我正在学习Python和编程,但不太确定该如何完成这个任务。
书中有一个例子是把字母正着显示出来,但我不知道怎么做到反过来显示。这个任务需要用到while循环。
fruit = 'banana'
index = 0
while index > len(fruit):
letter = fruit[index]
print letter
index = index + 1
4 个回答
1
最简单的方式是:
>>> def print_reversed(s):
... for letter in reversed(s):
... print letter,
...
>>> print_reversed('banana')
a n a n a b
>>>
另一种可能的解决方案是将索引设置为字符串的最后一个位置。然后你可以从后往前一个字母一个字母地读取字符串,每次将索引值减1。这样你展示的代码片段就可以变成:
>>> 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
>>>
使用交互式解释器(只需在命令提示符中输入'python')可以帮助你尝试这些代码片段。比如说:
>>> 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
>>>
2
我觉得最简单的方法是
print ''.join(reversed('banana'))
或者,如果你想让每个字母单独一行的话
print '\n'.join(reversed('banana'))
我觉得这样更好,因为使用 join 是处理字符串的标准方法,所以...
5
好吧,其实这基本上是一样的,但有几点不同:
你需要从最后一个字母开始,而不是第一个,所以你要用
index = len(fruit) - 1
,而不是index = 0
。在 while 循环的最后,你需要 减小 索引,而不是增加它,所以
index = index + 1
变成index = index - 1
。while 循环的条件也不同;你希望在循环中继续,直到
index
指向一个有效的字符索引。因为index
是从len(fruit) - 1
开始的,并且每次循环后会减小,所以最终它会变得小于零。零仍然是一个有效的字符索引(它指的是字符串的第一个字符),所以你希望在循环中继续,直到index >= 0
-- 这就是while
的条件。
把这些都放在一起:
fruit = 'banana'
index = len(fruit) - 1
while index >= 0:
letter = fruit[index]
print letter
index = index - 1