There is no built in reverse
function for Python\'s str
object. What is the best way of implementing this method?
If supplying a very conci
Sure, in Python you can do very fancy 1-line stuff. :)
Here's a simple, all rounder solution that could work in any programming language.
def reverse_string(phrase):
reversed = ""
length = len(phrase)
for i in range(length):
reversed += phrase[length-1-i]
return reversed
phrase = raw_input("Provide a string: ")
print reverse_string(phrase)
This is also an interesting way:
def reverse_words_1(s):
rev = ''
for i in range(len(s)):
j = ~i # equivalent to j = -(i + 1)
rev += s[j]
return rev
or similar:
def reverse_words_2(s):
rev = ''
for i in reversed(range(len(s)):
rev += s[i]
return rev
Another more 'exotic' way using byterarray which supports .reverse()
b = bytearray('Reverse this!', 'UTF-8')
b.reverse()
b.decode('UTF-8')
will produce:
'!siht esreveR'
@Paolo's s[::-1]
is fastest; a slower approach (maybe more readable, but that's debatable) is ''.join(reversed(s))
.
This is simple and meaningful reverse function, easy to understand and code
def reverse_sentence(text):
words = text.split(" ")
reverse =""
for word in reversed(words):
reverse += word+ " "
return reverse
Here is a no fancy one:
def reverse(text):
r_text = ''
index = len(text) - 1
while index >= 0:
r_text += text[index] #string canbe concatenated
index -= 1
return r_text
print reverse("hello, world!")
Recursive method:
def reverse(s): return s[0] if len(s)==1 else s[len(s)-1] + reverse(s[0:len(s)-1])
example:
print(reverse("Hello!")) #!olleH