11

How do I 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 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 :)

7
  • 1
    If you manage to outsmart the interviewer by pretending you know absolute basic stuff where in fact you do not, what will happen if you get the job and will have to do real work? Commented Sep 18, 2013 at 12:48
  • Haha, i didnt it:) and that's why i asked you:) Commented Sep 18, 2013 at 12:59
  • 1
    @VadimKovrizhkin Reverse a string in python without using reversed or [::-1]. Commented Sep 18, 2013 at 13:01
  • I did it like [::-1] And this answer didnt like them Commented Sep 18, 2013 at 13:02
  • So basically, you're asking how to implement a low-level programming construct in a high-level language. I remember having to do this kind of stuff in a C++ class with pointers and all. The point of such an exercise is to know HOW these constructs work, and thus what kind of limitations, space- or time-wise, various options have. Commented Sep 22, 2013 at 2:31

3 Answers 3

20
>>> 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:

>>> 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'
Sign up to request clarification or add additional context in comments.

9 Comments

No, I no about this [::-1] but on interview, i must did this without [::-1] just cycle.
Do you want a reverse looping logic?
@VadimKovrizhkin check updated answer, is it what you wanted?
Can you do this without xrange?
@VadimKovrizhkin why? Is this or requirement or it doesn't work for you? Then, may be you are on python 3 - use range() instead of xrange().
|
4

Use the slice notation:

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

You can read more about the slice notatoin here.

Comments

2

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 is the best programming language"[::-1]

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

[::-1] traverses an array from end to start, one character at a time.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.