Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reverse words in Python [duplicate]

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

like image 878
Vadim Kovrizhkin Avatar asked Sep 18 '13 12:09

Vadim Kovrizhkin


People also ask

How do you reverse a string in Python?

The reversed() Built-in Functionjoin() to create reversed strings. However, the main intent and use case of reversed() is to support reverse iteration on Python iterables. With a string as an argument, reversed() returns an iterator that yields characters from the input string in reverse order.

How do you reverse all words in a list Python?

In Python, you can reverse the items of lists ( list ) with using reverse() , reversed() , and slicing. If you want to reverse strings ( str ) and tuples ( tuple ), use reversed() or slice.


2 Answers

>>> 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'
like image 179
alecxe Avatar answered Oct 04 '22 18:10

alecxe


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.

like image 23
wmgaca Avatar answered Oct 04 '22 19:10

wmgaca