如何让 Python 向后打印输入的消息?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13978387/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 10:04:46  来源:igfitidea点击:

How can I get Python to print an entered message backwards?

pythonreverseslice

提问by Micrified

Possible Duplicate:
Reverse a string in Python

可能的重复:
在 Python 中反转字符串

Its been stumping me despite my initial thoughts that it would be simple.

尽管我最初认为这很简单,但它一直困扰着我。

Originally, I thought I would have have it print the elements of the string backwards by using slicing to have it go from the last letter to the first.

最初,我想我会通过使用切片让它从最后一个字母到第一个字母来向后打印字符串的元素。

But nothing I've tried works. The code is only a couple lines so I don't think I will post it. Its extraordinarily frustrating to do.

但我尝试过的一切都不起作用。代码只有几行,所以我不认为我会发布它。这样做非常令人沮丧。

I can only use the " for ", "while", "If" functions. And I can use tuples. And indexing and slicing. But thats it. Can somebody help?

我只能使用“for”、“while”、“If”函数。我可以使用元组。以及索引和切片。但就是这样。有人可以帮忙吗?

(I tried to get every letter in the string to be turned into a tuple, but it gave me an error. I was doing this to print the tuple backwards which just gives me the same problem as the first)

(我试图让字符串中的每个字母都变成一个元组,但它给了我一个错误。我这样做是为了向后打印元组,这给我带来了与第一个相同的问题)

I do not know what the last letter of the word could be, so I have no way of giving an endpoint for it to count back from. Nor can I seem to specify that the first letter be last and all others go before it.

不知道这个词的最后一个字母是什么,所以我无法给出一个可以倒计时的端点。我似乎也不能指定第一个字母在最后,所有其他字母在它之前。

回答by Mike Christensen

You can do:

你可以做:

>>> 'Hello'[::-1]
'olleH'

Sample

样本

回答by jdotjdot

As Mike Christensenabove wrote, you could easily do 'Hello'[::-1].

正如上面的Mike Christensen所写,您可以轻松地做到'Hello'[::-1].

However, that's a Python-specific thing. What you could do in general if you're working in other languages, including languages that don't allow for negative list slicing, would be something more like:

但是,这是 Python 特有的事情。如果您使用其他语言(包括不允许负面列表切片的语言),通常可以做的事情更像是:

def getbackwards(input_string):
   output = ''
   for x in range(0,len(input_string),-1):
       output += input_string[x]
   return output

You of course would not actually do this in Python, but just wanted to give you an example.

您当然不会在 Python 中实际执行此操作,而只是想举个例子。