如何在Python中反转单词

2024-09-21 11:42:58 发布

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

如何在Python中反转单词?

例如:

SomeArray=('Python is the best programming language')
i=''
for x in SomeArray:
      #i dont know how to do it

print(i)

结果必须是:

egaugnal gnimmargorp tseb eht si nohtyP

请帮忙。并解释。
备注:
我不能用[::-1]。我知道这件事。我必须在面试中这样做,只使用循环:)


Tags: thetoinforisit单词do
3条回答

使用切片符号:

>>> string = "Hello world."
>>> reversed_string = string[::-1]
>>> print reversed_string
.dlrow olleH

您可以在here中阅读有关切片notatoi的更多信息。

Python中的字符串是一个字符数组,因此您只需向后遍历数组(字符串)。你可以这样做:

"Python is the best programming language"[::-1]

这将返回"egaugnal gnimmargorp tseb eht si nohtyP"

[::-1]从头到尾遍历数组,一次遍历一个字符。

>>> s = 'Python is the best programming language'
>>> s[::-1]
'egaugnal gnimmargorp tseb eht si nohtyP'

升级版:

如果您需要在一个循环中执行此操作,可以使用range返回:

>>> result = ""
>>> for i in xrange(len(s)-1, -1, -1):
...     result += s[i]
... 
>>> result
'egaugnal gnimmargorp tseb eht si nohtyP'

或者,reversed()

>>> result = ""
>>> for i in reversed(s):
...     result += i
... 
>>> result
'egaugnal gnimmargorp tseb eht si nohtyP'

相关问题 更多 >

    热门问题