Python - 编写一个函数,以字符串作为参数并向后显示字母,每行一个
这是“如何像计算机科学家一样思考”中的练习。我正在学习 Python/编程,但我不知道如何完成这项任务。
这是书中的一个例子,向前显示字母,我不知道如何获得相反的效果。必须使用 while 循环。
fruit = 'banana'
index = 0
while index > len(fruit):
letter = fruit[index]
print letter
index = index + 1
This is an exercise from "How to think like a Computer Scientist". I am learning Python/programming and I'm not sure how to do accomplish this task.
Here is an example in the book that displays the letters forwards, I can't figure out how to get the opposite effect. Has to use a while-loop.
fruit = 'banana'
index = 0
while index > len(fruit):
letter = fruit[index]
print letter
index = index + 1
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
嗯,基本上是一样的,但是:
您必须从最后一个字母而不是第一个字母开始,因此您需要
index = len,而不是
index = 0
(fruit) - 1您必须减少索引,而不是在 while 循环结束时增加索引,因此
index = index + 1
变为index = index - 1
。while循环的条件不同;只要
index
指向有效的字符索引,您就希望留在循环内。由于index
从len(fruit) - 1
开始,每次迭代后它都会变小,最终它会变得小于零。零仍然是一个有效的字符索引(它指的是字符串的第一个字符),因此只要index >= 0
,您就希望留在循环中 - 这将是while
条件。把它们放在一起:
Well, it's basically the same thing, but:
You have to start from the last letter instead of the first, so instead of
index = 0
, you'll needindex = len(fruit) - 1
You have to decrease the index instead of increasing it at the end of the while loop, so
index = index + 1
becomesindex = index - 1
.The condition of the while loop is different; you want to stay within the loop as long as
index
points to a valid character index. Sinceindex
starts fromlen(fruit) - 1
and it gets one smaller after every iteration, eventually it will get smaller than zero. Zero is still a valid character index (it refers to the first character of the string), so you'll want to stay within the loop as long asindex >= 0
-- this will be thewhile
condition.Putting it all together:
我认为最简单的方法是
或者,如果你想要每行一个字母,
我认为它更好,因为 join 是操作字符串的标准方法,所以......
i think that the simplest way is
or, if you want one letter per line
i think it's better because join is the standard way to operate on strings, so...
最简单的是:
其他可能的解决方案可能是将索引设置为字符串的最后一个索引。然后,您将逐个字母地向后读取字符串,每次将索引值减 1。然后,您显示的代码片段可能会变成:
使用交互式解释器(只需在命令提示符中键入“python”)可以帮助您试验此类代码片段。例如:
Simplest as:
Other possible solution could be putting the index to be the last index of the string. Then you are going to read the string letter by letter backwards, lowering the index value by 1 each time. Then the code snipplet that you showed could become:
Using the interactive interpreter (just type 'python' in a command prompt) could help you experiment with such code snipplets. Like for example:
这可能有助于接收任何单词并返回其反向文件
This may helping receive any word and return its reversed le