3

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?

7
  • Are you trying to reverse the string or print the characters in reverse order? Your title implies the former but your code seems to be trying to do the latter. If you want to reverse the string -- build it up and then return the reversed string. Let the calling code print it if it wants. Most functions shouldn't have print in them. Commented Dec 25, 2016 at 15:23
  • You could use a temp variable to build the reversed string instead of manipulating the original string Commented Dec 25, 2016 at 15:23
  • del modifies an object, but you cannot modify a string, you must create a new string instead. Try creating a new string with one character fewer: text = text[:-1] Commented Dec 25, 2016 at 15:23
  • @Duncan true enough -- but pointless. OP has no good reason for trying to make the string smaller in the course of building up the reverse. Commented Dec 25, 2016 at 15:24
  • 1
    @Duncan I wouldn't say that a quadratic algorithm for reversing a string is perfectly valid, although it is of course valid. Creating a copy of the string at each stage is expensive. Commented Dec 25, 2016 at 15:31

4 Answers 4

7

Python string is not mutable, so you can not use the del statement to remove characters in place. However you can build up a new string while looping through the original one:

def reverse(text):
    rev_text = ""
    for char in text:
        rev_text = char + rev_text
    return rev_text

reverse("hello")
# 'olleh'
Sign up to request clarification or add additional context in comments.

2 Comments

I'm not quite sure that a complete answer benefits OP as much as a hint would.
@JacobVlijm s[::-1] is the only answer that benefits someone not doing a homework assignment. In any event -- surely this must be a duplicate.
5

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

8 Comments

Ok i understand but i dont understand the len(text) + 1
Why do you use + 1 for i to iterate through?
@DanielBäck It's only there because python was missing the last letter of the reversed word. To fix this I just added one so that it would loop once more and add the final letter.
okay i see thank you this solved my problem!
Hi @DanielBäck if this or any answer has solved your question please consider accepting it by clicking the check-mark. This indicates to the wider community that you've found a solution and gives some reputation to both the answerer and yourself.
|
1

Python strings are immutable. You cannot use del on string.

text = 'abcde'
length = len(text)
text_rev = ""
while length>0:
   text_rev += text[length-1]
   length = length-1

print text_rev

Hope this helps.

3 Comments

Yeah its cool to se you can also use a while loop for it,
This one seems easier than using the for loop
@Daniel Bäck You can upvote my solution if you like it. That helps some one who is looking for same kind of answer like you.
0

Here is my attempt using a decorator and a for loop. Put everything in one file.

Implementation details:

def reverse(func):
    def reverse_engine(items):
        partial_items = []
        for item in items:
            partial_items = [item] + partial_items
        return func(partial_items)
    return reverse_engine

Usage:

Example 1:

@reverse
def echo_alphabets(word):
    return ''.join(word)

echo_alphabets('hello')
# olleh

Example 2:

@reverse
def echo_words(words):
    return words

echo_words([':)', '3.6.0', 'Python', 'Hello'])
# ['Hello', 'Python', '3.6.0', ':)']

Example 3:

@reverse
def reverse_and_square(numbers):
    return list(
        map(lambda number: number ** 2, numbers)
    )

reverse_and_square(range(1, 6))
# [25, 16, 9, 4, 1]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.