KRS-fun
KRS-fun

Reputation: 724

Python String Reversal

This exercise involves a codeacademy problem to write a function which takes a string as an input and outputs the string in reverse, I've found solutions as to how to do it online, I'm just confused as to why mine doesnt work:

def reverse(c):
    empty=[]
    stringsize= len(c)

    for x in range(stringsize):
        empty[x]=c[stringsize-x]

    return empty

Upvotes: 0

Views: 162

Answers (5)

James Sapam
James Sapam

Reputation: 16930

One solution :

def reverse(c):
    empty=[]
    stringsize= len(c)
    for x in range(stringsize):
        empty.append(c[-(x+1)])
    return ''.join(empty)

print reverse('string')

Another:

    def reverse(c):
    empty=[]
    stringsize= len(c)
    for x in range(stringsize):
        empty.append(c[stringsize - (x+1)])
    return ''.join(empty)

print reverse('string')

Using recursion:

    def reverse(string,start,stop):
    if start < stop - 1:
        string[start],string[stop - 1] = string[stop - 1],string[start]
        reverse(string,start+1, stop-1)
    return ''.join(string)

print reverse(list('string'), 0, len('string'))

Upvotes: 2

Martijn Pieters
Martijn Pieters

Reputation: 1121148

You need to start at indexing your string from -1 through to -stringsize, and use empty.append() to add values:

for x in range(stringsize):
    empty.append(c[stringsize - x - 1])

Python indexing starts at 0, making stringsize - 1 the last index. Because empty is an empty list, you cannot index into it. Using the list.append() method adds new values at the end instead.

You don't really need the stringsize reference there, because negative indices automatically are subtracted from the length for you:

for x in range(len(c)):
    empty.append(c[-x-1])

Since this is supposed to return a string, not a list, you need to join the characters again at the end:

return ''.join(empty)

The easiest way to reverse a list is to use a negative slice stride:

def reverse(c):
    return c[::-1]

Upvotes: 4

Wolf
Wolf

Reputation: 4452

The classic answer to this problem is to use a slice with a negative step to get what you want:

def reverse(c):
    return c[::-1]

...but maybe that's not allowed for you?

Upvotes: 1

Alfe
Alfe

Reputation: 59416

The least changes necessary to make your code run seem to be:

def reverse(c):
    stringsize= len(c)
    empty=[None] * stringsize

    for x in range(stringsize):
        empty[x]=c[stringsize-x-1]

    return empty

But you should reconsider your name empty (as Martijn pointed out) because that thing isn't empty (at least in the end), so the name is misleading.

Upvotes: 1

Alex Plugaru
Alex Plugaru

Reputation: 2249

In Python a string is an iterable so iterable functions can be used with it. For example reversed function:

>>> "".join(reversed("123"))
'321'

Upvotes: 1

Related Questions