How to reverse words in Python

How to reverse words in 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 should be:

 egaugnal gnimmargorp tseb eht si nohtyP 

please, help. And explain.
PS:
I can not use [::-1] . I know about it. I have to do this in an interview using only loops :)

+4
source share
3 answers
 >>> s = 'Python is the best programming language' >>> s[::-1] 'egaugnal gnimmargorp tseb eht si nohtyP' 

UPD:

if you need to do this in a loop, you can use a range to go backward:

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

or, reversed() :

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

Use slice notation:

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

Read more about the noatoin fragment here.

+3
source

A string in Python is an array of characters, so you just need to go back the array (string). You can do it as follows:

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

This will return "egaugnal gnimmargorp tseb eht si nohtyP" .

[::-1] moves the array from start to start, one character at a time.

0
source

Source: https://habr.com/ru/post/1502799/


All Articles