What is the best way to loop over a python string backwards?
The following seems a little awkward for all the need of -1 offset:
string = \"trick or
string reverse
def reverse(a_string):
rev = ''
for i in range(len(a_string)-1, -1, -1):
rev = rev + a_string[i]
return rev
print(reverse("This string should be reversed!"))
output is: !desrever eb dluohs gnirts sihT
string = "trick or treat"
for c in string[::-1]:
print c
I would use that. It is probably quite fast although there may be a slightly better way (but I doubt it).
EDIT:
Actually, with a second test using a program I hacked together, reversed
is probably the way to go.
==== Results ====
Sample 1: 0.0225071907043 # Using a for loop
Sample 2: 0.0100858211517 # Using reversed
def reverse(text):
x = ""
for i in range(len(text)):
x = x + text[len(text)-i-1]
return x
Reverse a String in Python using For Loop
outputStr = ''
a = raw_input("Enter String: ")
for i in range(len(a), 0, -1):
outputStr += a[i-1]
print outputStr
string = "trick or treat"
for c in reversed(string):
print c
Will do what I think you want. It uses an iterator. This should work with anything that has __reveresed__() or __len__() and __getitem__() implemented. __getitem__() would have to take int arguments starting at 0.
Here is a way to reverse a string without utilizing the built in features such as reversed
. Negative step values traverse backwards.
def reverse(text):
rev = ''
for i in range(len(text), 0, -1):
rev += text[i-1]
return rev