Python—编写一个函数,该函数以字符串作为参数,并向后显示字母,每个lin一个

2024-05-23 21:16:25 发布

您现在位置:Python中文网/ 问答频道 /正文

这是“如何像计算机科学家一样思考”的练习。我正在学习Python/programming,我不知道如何完成这项任务。

这是本书中的一个例子,显示的是向前的字母,我不知道如何得到相反的效果。必须使用while循环。

fruit = 'banana'
index = 0
while index > len(fruit):
        letter = fruit[index]
        print letter
        index = index + 1

Tags: indexlen计算机字母例子programmingbanana科学家
3条回答

最简单的是:

>>> 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”)可以帮助您尝试使用这种代码snipplet。例如:

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

我认为最简单的方法是

print ''.join(reversed('banana'))

或者,如果你想每行写一封信

print '\n'.join(reversed('banana'))

我认为这更好,因为连接是操作字符串的标准方法,所以。。。

基本上是一样的,但是:

  1. 你必须从最后一个字母开始,而不是从第一个字母开始,所以你需要index = 0,而不是index = len(fruit) - 1

  2. 你必须在while循环结束时减少而不是增加索引,所以index = index + 1变成index = index - 1

  3. while循环的条件不同;只要index指向有效的字符索引,您就希望留在循环中。因为indexlen(fruit) - 1开始,每次迭代后它会变小一个,最终它会变小到小于零。零仍然是一个有效的字符索引(它指的是字符串的第一个字符),因此只要index >= 0——这将是while条件,您就需要保持在循环中。

总而言之:

fruit = 'banana'
index = len(fruit) - 1
while index >= 0:
    letter = fruit[index]
    print letter
    index = index - 1

相关问题 更多 >