Python Forum

Full Version: I am trying to reverse a string using loop
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi, I recently started learning python, I read this blog and trying to implementing it.

I am getting stuck, I can't use ".join(reversed(string)) or string[::-1] methods here

Here is what my code looks like:

def reverse(text):
    while len(text) > 0:
        print text[(len(text)) - 1],
        del(text[(len(text)) - 1]
The error that I an getting is, invalid syntax on del(text[(len(text)) - 1]

Please suggest to me where I went wrong.

Thank you!
Python 3 print needs to be used with ()
to get the last item of text text[(len(text)) - 1] can be replaced with text[-1]
to get all but the last item text = text[:-1]
def reverse(text):
    while len(text) > 0:
        print(
            text[-1]
        )
        text = text[:-1]
Thank you for the quick response, I will try this.
Count the number of open parentheses ( and close parentheses ) in:
del(text[(len(text)) - 1]
If the number is not the same then that is a problem.
Hi,

you know all these simple things we amateurs want to try, someone has already done them.

Have a look here.