I'm stuck at an exercise where I need to reverse a random string in a function using only a loop (for loop or while?).
I can not use ".join(reversed(string)) or string[::-1] methods here so it's a bit tricky.
My code looks something like this:
def reverse(text):
while len(text) > 0:
print text[(len(text)) - 1],
del(text[(len(text)) - 1]
I use the , to print out every single letter in text on the same line!
I get invalid syntax on del(text[(len(text)) - 1]
Any suggestions?
解决方案
The problem is that you can't use del on a string in python.
However this code works without del and will hopefully do the trick:
def reverse(text):
a = ""
for i in range(1, len(text) + 1):
a += text[len(text) - i]
return a
print(reverse("Hello World!")) # prints: !dlroW olleH