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?

Tonechas
  • 13,398
  • 16
  • 46
  • 80
Daniel B
  • 111
  • 1
  • 2
  • 8
  • 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. – John Coleman Dec 25 '16 at 15:23
  • You could use a temp variable to build the reversed string instead of manipulating the original string – Mike Scotty Dec 25 '16 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]` – Duncan Dec 25 '16 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. – John Coleman Dec 25 '16 at 15:24
  • i want to reverse the string, for example def reverse("abcd") should return "dcba" – Daniel B Dec 25 '16 at 15:26
  • @JohnColeman, his approach will work by deleting the end character from the string (except he should probably be building up the reversed string in a variable rather than printing a character at a time) but "save last character then remove last character from the string" is a perfectly valid way to reverse it. – Duncan Dec 25 '16 at 15:27
  • 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. – John Coleman Dec 25 '16 at 15:31

4 Answers4

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'
Psidom
  • 209,562
  • 33
  • 339
  • 356
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
EDD
  • 2,070
  • 1
  • 10
  • 23
  • Ok i understand but i dont understand the len(text) + 1 – Daniel B Dec 25 '16 at 15:42
  • Why do you use + 1 for i to iterate through? – Daniel B Dec 25 '16 at 15:43
  • @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. – EDD Dec 25 '16 at 15:43
  • okay i see thank you this solved my problem! – Daniel B Dec 25 '16 at 15:47
  • 1
    Hi @DanielBäck if this or any answer has solved your question please consider [accepting it](http://meta.stackexchange.com/q/5234/179419) 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. – EDD Dec 25 '16 at 15:54
  • ok but i can only accept 1 solution right? – Daniel B Dec 25 '16 at 16:00
  • @DanielBäck Yes, only one. – EDD Dec 25 '16 at 16:01
  • reversed = ''"; for i in range(len('123')): reversed += '123'[(i+1)*-1] – Yasir Jan Aug 28 '18 at 07:41
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.

Teja
  • 436
  • 5
  • 11
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]
Eddie
  • 1,043
  • 8
  • 14