Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to reverse a plain string? 1

Status
Not open for further replies.

Stoad

Programmer
Jan 4, 2004
4
BY
I can't find anything for the subject.
Need something like this:

s='qwerty'
s=s.reverse()
print s

ytrewq
>>>
 
In python2.3:
Code:
>>> print '1233456789'[::-1]
9876543321

In earlier versions:
Code:
>>> l = list( '123456789' )
>>> l.reverse()
>>> print "".join( l )
987654321

or with a little more obfuscation:
Code:
>>> print reduce(lambda x,y: y+x, '123456789')
987654321
 
wow! incredible! thanks a lot eric!
 
eric, could you please explain how that last one works?
 
lambda is a computer science construct for creating an undeclared, unnamed function. I think I first saw it in lisp.

saying:
Code:
x=lambda a: a + 1

is the same as:
Code:
def x( a ):
  return a + 1

Notice that lambda has the effect of implicitly returning the result of its last operation.

reduce takes members of a list and successively (not recursively) applies a function to each member of the list accumulating the result. From the manual:

reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5)

So, to understand the last example, just remember that + is the string concatenation operator and a string is a list that reduce will iterate over.

Note that I *never* use lambdas in my code, you never remember what you were trying to do when your debugging the code 6 months later. It really only exists to make you look cool. :)
 
I've seen lambda and reduce before, in Lisp. My problem was not realizing that + was concatenation rather than addition and that a string was a list. (I fooled around with Python a while back, then let it drop.) I get it now. Thanks!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top