7. Reverse


Woohoo! first one in a while i've been able to get without going to the Q&A on this section. I'm definitely going to have to go over this section again, but I feel like my code is just so messy and probably way longer than it needs to be. Can anyone give me some pointers for how to cut down on the code?


def reverse(string):
    lst = []                                #create an empty list
    revlst = []
    string = str(string)                    #make sure the variable is a string
    for i in string:                        #take each letter in the string
        lst.append(i)                       #append to the list
    a = len(lst)                            #get length of the list
    for i in string:                        #for each letter in the string
        revlst.append(lst[a-1])             #append in reverse
        a -= 1                              #count backwards to append to newlist
    con_revlst = ''.join([str(mli) for mli in revlst]) 
                                            #join the reversed list into a new list
    return con_revlst
print reverse("helpwhoknow!swhatsgoinon")

Also just making sure I can format correctly when posting to Q&A...



There is always room for improvement as always.

Python Example:

def reverse(text):
    return ''.join(letter for letter in list(text)[::-1])

As simple as this!

Any question feel free to ask.


Hah, yes I did see that [::-1], but the problem says not to use that :stuck_out_tongue:



If you want to be picky,

Python Code:

def reverse(text):
    return ''.join(letter for letter in (text[(index + 1) * -1] for index, char in enumerate(text)))

Happy now? It looks more confusing don't it though?


I don't know .

def reverse(text):
if not text == str(text):
return False
while x in range(len(text)) < len(text)-1:
print text[len(text)-1],
else :
print "this is the reverse sentence"



very much so...

gimme a minute to figure that out!


This is my own approach:

def reverse (text):
    rev = ""                    # A variable to store the reverse words
    i = len(text)               # Get the string length
    while i > 0:                # while the text is active
        rev += text[i-1:i]      #  join the alphabets in reverse
    return rev


def reverse(text):
output = ""
for letter in text:
output = letter + output
return output


Whilst far from perfect, I just wanted to share my working approach. One thing I noticed is that the exercise won't let you go through if you try to print the joint result instead of just returning it.

def reverse(text):
    index = len(text) - 1
    result = []
    for char in text:
        index -= 1
    return "".join(result)
print reverse("Python!")


Or that variant:

def reverse(text):
    count = len(text) - 1
    txt_reverse = ""
    while count >= 0:
        txt_reverse += text[count]
        count -= 1
    return txt_reverse


This seems to be working...

def reverse(text):
l = len(text)
result = ''
print l
while l > 0:
l -= 1
return str(result)

Yet another possible solution. First one I could get without the Q&A.

def reverse(text):
    ls = []
    rev_ls = []
    for char in text:
    while ls != []:
    reverse = "".join(rev_ls)
    return reverse


def reverse(text):
txt_lst = []
r_txt = ""
for i in text:
while len(txt_lst) > 0:
r_txt = r_txt + txt_lst.pop()
return r_txt

Apologies if this is redundant, but I didn't see anyone use list.pop()
It seems to work!


We can do this in one statement...

    txt_lst = list(text)

The .pop() method has been demonstrated before, but maybe just not in the new forums (post October 1st). We can use an augmentation operator to assign members to r_txt.

    r_txt += txt_lst.pop()


Thanks for the help; I'm a big fan of concision.


Mine gives me an error. Could somebody help?

Oops, try again. Your code looks a bit off--it threw a "string index out of range" error. Check the Hint if you need help!


I figured it out:
changed l from 0 to 1
and while condition from l


Thanks so much! Very useful!!! I completed mine a very long way - yours is really concise though!!!


Hi , please help to check my code, it always pop part of the chars.

def reverse(text):
str = []
str2 = []
final_str = ''
for char in text:
print "str is ", str
for i in str:
temp = str.pop()
print "pop is :",temp

print "str2 is ", str2
final_str = ''.join(str2)    
print "final_str is ", final_str
return final_str

The the result is as following:
C:\Python27>python piggame.py
Input string: abcde
str is ['a', 'b', 'c', 'd', 'e']
pop is : e
pop is : d
pop is : c
str2 is ['e', 'd', 'c']
final_str is edc


Who can tell me why after I upload the code then the indent disappears?