Reputation: 5673
I came across a strange Codecademy exercise that required a function that would take a string as input and return it in reverse order. The only problem was you could not use the reversed method or the common answer here on stackoverflow, [::-1]
.
Obviously in the real world of programming, one would most likely go with the extended slice method, or even using the reversed
function but perhaps there is some case where this would not work?
I present a solution below in Q&A style, in case it is helpful for people in the future.
Upvotes: 42
Views: 186942
Reputation: 31
Try this simple and elegant code.
my_string= "sentence"
new_str = ""
for i in my_string:
new_str = i + new_str
print(new_str)
Upvotes: 1
Reputation: 543
I have got an example to reverse strings in python from thecrazyprogrammer.com:
string1 = "IkNoWwHeReYoUlIvE"
string2 = ""
i = len(string1)-1
while(i>=0):
string2 = string2 + string1[i]
i = i-1
print("original = " + string1)
print("reverse = " + string2)
Upvotes: 0
Reputation: 840
simply run this but it would print each character in a separate line the second version prints it in one line.
def rev(str):
for i in range(0,len(str)):
print(list(str)[len(str)-i-1])
Print in one line:
def rev(str):
rev = list()
for i in range(0,len(str)):
rev.append((list(str)[len(str)-i-1]))
print(''.join(rev))
Upvotes: 0
Reputation: 20187
Simple Method,
>>> a = "hi hello"
>>> ''.join([a[len(a)-i-1] for i,j in enumerate(a)])
'olleh ih'
>>>
Upvotes: 0
Reputation: 450
You can simply use the pop as suggested. Here are one liners fot that
chaine = 'qwertyuiop'
''.join([chaine[-(x + 1)] for x in range(len(chaine))])
'poiuytrewq'
gg = list(chaine)
''.join([gg.pop() for _ in range(len(gg))])
'poiuytrewq'
Upvotes: 0
Reputation: 1185
I prefer this as the best way of reversing a string using a for loop.
def reverse_a_string(str):
result=" "
for i in range(len(str),1,-1):
result= result+ str[i-1]
return result
print reverse_a_string(input())
Upvotes: 0
Reputation: 3081
Here is one using a list as a stack:
def reverse(s):
rev = [_t for _t in s]
t = ''
while len(rev) != 0:
t+=rev.pop()
return t
Upvotes: 1
Reputation: 12679
We can first convert string into a list and then reverse the string after that use ".join" method to again convert list to single string.
text="Youknowwhoiam"
lst=list(text)
lst.reverse()
print("".join(lst))
It will first convert "youknowwhoiam" into ['Y', 'o', 'u', 'k', 'n', 'o', 'w', 'w', 'h', 'o', 'i', 'a', 'm']
After it will reverse the list into ['m', 'a', 'i', 'o', 'h', 'w', 'w', 'o', 'n', 'k', 'u', 'o', 'Y']
In last it will convert list into single word "maiohwwonkuoY "
For more explanation in brief just run this code:-
text="Youknowwhoiam"
lst=list(text)
print (lst)
lst.reverse()
print(lst)
print("".join(lst))
Upvotes: -1
Reputation: 11
__author__ = 'Sreedhar'
#find reverse of the string with out using index or reverse function?
def reverse(text):
revs = ""
for i in text:
revs = i + revs
return revs
strig = raw_input("enter anything:")
print reverse(strig)
#index method
print strig[::-1]
Upvotes: -3
Reputation: 894
enterString=input("Enter a string to be reversed:")
string_List=list(enterString)
revedString=[]
for i in range(len(string_List)):
revedString.append(string_List.pop())
#Pop last element and append it to the empty list
print "reversed string is:",''.join(revedString)
#as the out come is in list convert it into string using .join
Sample Output:
>>>Enter a string to be reversed :sampleReverse1
>>>reversed string is:1esreveRelpmas
Upvotes: 0
Reputation: 7
Easiest way to reverse a string:
backwards = input("Enter string to reverse: ")
print(backwards[::-1])
Upvotes: -8
Reputation: 11
m = input("Enter string::")
def rev(s):
z = -1
x = len(s)
while x != 0:
print(s[z], end='')
z = z-1
x = x-1
rev(m)
Upvotes: 0
Reputation: 974
You can do simply like this
def rev(str):
rev = ""
for i in range(0,len(str)):
rev = rev + str[(len(str)-1)-i]
return rev
Upvotes: 1
Reputation: 4496
Blender's answer is lovely, but for a very long string, it will result in a whopping RuntimeError: maximum recursion depth exceeded
. One might refactor the same code into a while loop, as one frequently must do with recursion in python. Obviously still bad due to time and memory issues, but at least will not error.
def reverse(text):
answer = ""
while text:
answer = text[0] + answer
text = text[1:]
return answer
Upvotes: 2
Reputation: 279
def reverse(text):
rev = ""
final = ""
for a in range(0,len(text)):
rev = text[len(text)-a-1]
final = final + rev
return final
Upvotes: 0
Reputation: 319
def reverse(s):
return "".join(s[i] for i in range(len(s)-1, -1, -1))
Upvotes: 2
Reputation: 205
Here's my contribution:
def rev(test):
test = list(test)
i = len(test)-1
result = []
print test
while i >= 0:
result.append(test.pop(i))
i -= 1
return "".join(result)
Upvotes: 1
Reputation: 2024
This is my solution using the for i in range loop:
def reverse(string):
tmp = ""
for i in range(1,len(string)+1):
tmp += string[len(string)-i]
return tmp
It's pretty easy to understand. I start from 1 to avoid index out of bound.
Upvotes: 1
Reputation: 21
def reverseThatString(theString):
reversedString = ""
lenOfString = len(theString)
for i,j in enumerate(theString):
lenOfString -= 1
reversedString += theString[lenOfString]
return reversedString
Upvotes: 1
Reputation: 9
My solution:
s = raw_input("Enter string ")
print
def reverse(text):
st = ""
rev = ""
count = len(text)
print "Lenght of text: ", len(text)
print
for c in range(len(text)):
count = count - 1
st = st + "".join(text[c])
rev = rev + "".join(text[count])
print "count: ", count
print "print c: ", c
print "text[c]: ", text[c]
print
print "Original: ", st
print "Reversed: ", rev
return rev
reverse(s)
Result screen
Enter string joca
Lenght of text: 4
count: 3
print c: 0
text[c]: j
count: 2
print c: 1
text[c]: o
count: 1
print c: 2
text[c]: c
count: 0
print c: 3
text[c]: a
Original: joca
Reversed: acoj
None
Upvotes: 0
Reputation: 1
The way I can think of without using any built-in functions:
a = 'word'
count = 0
for letter in a:
count += 1
b = ''
for letter in a:
b += a[count-1]
count -= 1
And if you print b:
print b
drow
Upvotes: 0
Reputation: 106
You've received a lot of alternative answers, but just to add another simple solution -- the first thing that came to mind something like this:
def reverse(text):
reversed_text = ""
for n in range(len(text)):
reversed_text += text[-1 - n]
return reversed_text
It's not as fast as some of the other options people have mentioned(or built in methods), but easy to follow as we're simply using the length of the text
string to concatenate one character at a time by slicing from the end toward the front.
Upvotes: 1
Reputation: 368
I used this:
def reverse(text):
s=""
l=len(text)
for i in range(l):
s+=text[l-1-i]
return s
Upvotes: 6
Reputation: 10162
Pointfree:
from functools import partial
from operator import add
flip = lambda f: lambda x, y: f(y, x)
rev = partial(reduce, flip(add))
Test:
>>> rev('hello')
'olleh'
Upvotes: 0
Reputation: 71
Only been coding Python for a few days, but I feel like this was a fairly clean solution. Create an empty list, loop through each letter in the string and append it to the front of the list, return the joined list as a string.
def reverse(text):
backwardstext = []
for letter in text:
backwardstext.insert(0, letter)
return ''.join(backwardstext)
Upvotes: 7
Reputation: 10172
You can simply reverse iterate your string starting from the last character. With python you can use list comprehension to construct the list of characters in reverse order and then join them to get the reversed string in a one-liner:
def reverse(s):
return "".join([s[-i-1] for i in xrange(len(s))])
if you are not allowed to even use negative indexing you should replace s[-i-1]
with s[len(s)-i-1]
Upvotes: 1
Reputation: 298364
You can also do it with recursion:
def reverse(text):
if len(text) <= 1:
return text
return reverse(text[1:]) + text[0]
And a simple example for the string hello
:
reverse(hello)
= reverse(ello) + h # The recursive step
= reverse(llo) + e + h
= reverse(lo) + l + e + h
= reverse(o) + l + l + e + h # Base case
= o + l + l + e + h
= olleh
Upvotes: 67
Reputation: 2172
Not very clever, but tricky solution
def reverse(t):
for j in range(len(t) // 2):
t = t[:j] + t[- j - 1] + t[j + 1:- j - 1] + t[j] + t[len(t) - j:]
return t
Upvotes: 0
Reputation: 11
All I did to achieve a reverse string is use the xrange
function with the length of the string in a for loop and step back per the following:
myString = "ABC"
for index in xrange(len(myString),-1):
print index
My output is "CBA"
Upvotes: 1