Question:
How do you reverse a string using a for loop in Python computer programming?
xpunkx
2011-10-13 02:21:21 UTC
I need a code that will reverse a string or list using a for loop.
I want to completely reverse the spelling of sentences and words without having to do it by hand.
Five answers:
anonymous
2011-10-13 02:31:06 UTC
Hi,



You could use slice notation to reverse a string, for example:



s = 'abcdef'

s = s[::-1]

print s



As for reversing a list there is a couple of ways.



a) Use the reversed function built into python:



>>> array=[0,10,20,30,40]

>>> for i in reversed(array):

... print i





b) Use the reverse method:



>>> A = [0,10,20,30,40]

>>> A.reverse()

>>> A





c) Use Slice:



>>> A=[0,10,20,30,40]

>>> A[::-1]





Regards,



Javalad
anonymous
2016-12-18 18:35:56 UTC
Reverse String Python
keva
2016-09-28 15:01:15 UTC
Python Reverse String
?
2017-01-19 02:26:20 UTC
1
husoski
2011-10-13 02:55:53 UTC
Sounds like an assignment. There are more direct ways to do this, like

s = "ABCDEF"

r = "".join(reversed(s))

print r



The reversed() built-in function returns an iterator, not a sequence, so you can't use it directly. But you can use it in a for loop:



r = ""

for ch in reversed(s) : r = r + ch

print r



This is ugly for large string because, if there are N characters in the string s, the reversed copy r will be assigned N+1 times. Strings are immutable, so to append a character to a string means creating an entirely new string that has the previous version's characters, plus the appended character(s). If you're using this approach, you don't need to use reversed(), either. Just rewrite the string assignment in the loop:



r = ""

for ch in s : r = ch + r

print r



The first version, using join, is probably the most efficient since it creates just one new string. If this is a class exercise and the instructions say to use a for loop, oh well. Use something like that last loop. It's the simplest.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...