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 :)
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.
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.
>>> 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'
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With