Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Program for word reversal randomly skips out letters?

Tags:

python

My program keeps randomly skipping out letters! For example, 'coolstory' becomes 'yrotsloc' and 'awesome' becomes 'mosewa'

Here is the code:

def reverse(text):
    length = len(text)
    reversed_text = []
    for i in range(0,length + 1):
        reversed_text += ['']
    original_list = []
    for l in text:
        original_list.append(l)
        new_place = length - (original_list.index(l))
        reversed_text[new_place] = l
    return "".join(reversed_text)

EDIT: Thanks for the answers everyone. I just rediscovered this forgotten account. I can assure you 6 years later I know how to properly reverse strings in a variety of different languages :)

like image 364
Ahraz Avatar asked Aug 19 '13 19:08

Ahraz


Video Answer


2 Answers

This happens when you have duplicate letters because

original_list.index(l)

will always return the same value for the same l. So new_place will be the same for two of the same letters at different locations.

One common way to reverse strings in Python is with slicing:

>>> s = "hello"
>>> s[::-1]
'olleh'

You can also use reversed(), but that returns a reversed object (not a string). This is a better option if you want to iterate over a string in reverse order:

>>> for c in reversed(s):
...     print c
... 
o
l
l
e
h
like image 52
arshajii Avatar answered Oct 22 '22 03:10

arshajii


Try

def reverse(text):
    return text[::-1]
like image 24
planestepper Avatar answered Oct 22 '22 05:10

planestepper