strings and sort()
Paul Rubin
phr-n2002a at nightsong.com
Wed Feb 20 21:01:29 EST 2002
caljason76 at yahoo.com (Jason) writes:
> How do I sort the characters in a string, so far I use this:
> a="qwerasdfzxcv"
> b=[x for x in a]
> b.sort()
You could also say
a = "qwerasdfzxcv"
b = list(a)
b.sort()
That might run a little faster than the list comprehension version,
plus it's more portable to older Python versions.
> Why doesn't sort() return the sorted list. I would like to chain it
> to other operations:
> b=[x for x in a].sort()
In Python, that's considered immoral--it puts you in danger of
forgetting that the sort operation modifies the list that you use it
on. For example, if you say
a = b.sort()
expecting to get a sorted copy of b without clobbering b, you'd get
a rude surprise.
More information about the Python-list
mailing list