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 :)
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
Try
def reverse(text):
return text[::-1]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With