如何在 Python 中反转单词
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18871841/
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
How to reverse words in Python
提问by Vadim Kovrizhkin
How do I reverse words in Python?
如何在 Python 中反转单词?
For instance:
例如:
SomeArray=('Python is the best programming language')
i=''
for x in SomeArray:
#i dont know how to do it
print(i)
The result must be:
结果必须是:
egaugnal gnimmargorp tseb eht si nohtyP
please help. And explain.
PS:
I can't use [::-1]
. I know about this. I must do this in an interview, using only loops :)
请帮忙。并解释。
PS:
我不能用[::-1]
。我知道这件事。我必须在面试中做到这一点,只使用循环:)
回答by alecxe
>>> s = 'Python is the best programming language'
>>> s[::-1]
'egaugnal gnimmargorp tseb eht si nohtyP'
UPD:
更新:
if you need to do it in a loop, you can use range to go backwards:
如果您需要在循环中执行此操作,则可以使用 range 向后移动:
>>> result = ""
>>> for i in xrange(len(s)-1, -1, -1):
... result += s[i]
...
>>> result
'egaugnal gnimmargorp tseb eht si nohtyP'
or, reversed()
:
或者,reversed()
:
>>> result = ""
>>> for i in reversed(s):
... result += i
...
>>> result
'egaugnal gnimmargorp tseb eht si nohtyP'
回答by zedutchgandalf
A string in Python is an array of chars, so you just have to traverse the array (string) backwards. You can easily do this like this:
Python 中的字符串是字符数组,因此您只需向后遍历数组(字符串)即可。你可以像这样轻松地做到这一点:
"Python is the best programming language"[::-1]
This will return "egaugnal gnimmargorp tseb eht si nohtyP"
.
这将返回"egaugnal gnimmargorp tseb eht si nohtyP"
。
[::-1]
traverses an array from end to start, one character at a time.
[::-1]
从头到尾遍历一个数组,一次一个字符。