invert the order of a string

rtilley rtilley at vt.edu
Mon Feb 13 14:22:13 EST 2006


Dave Hansen wrote:
> It's just simple slicing.  Well, maybe not so simple, or at least not
> so common, but with a syntax similar to the range function.  Consider
> the following (string chosen to make it obvious what's going on):
> 
> s = "0123456789"
> s[::]
> s[3::]
> s[:3:]
> s[::3]
> s[::-2]
> s[-2::-2]

Well, it turns out to be the best way to invert a string, IMO. The 
reversed() feature returns a reversed object... not a reversed string. 
In short, I have to fool with it again _after_ it has been inverted. The 
slicing takes care of the job right away and gives me what I want... no 
Computer Sciencey <reversed object at 0xb6f6152c>> to deal with :)

I'm sure the reversed feature is much more generic though for dealing 
with other types.



More information about the Python-list mailing list