A suggestion for a possible Python module
Martin Maney
maney at pobox.com
Sun Mar 9 21:28:17 EST 2003
In article <b4dqv9$str$1 at slb6.atl.mindspring.net> you wrote:
> Lance LaDamage:
>> > I have noticed that there is one thing that everyone wishes to do
>> > ... in Python reverse a string.
>
> Mark VandeWettering:
>> Honestly, what commonly programmed task requires string reversal? I can't
>> ever remember doing it even once during 20+ years of programming.
>
> The ones I could think of are:
> - insert commas in a number, as in "10000" -> "10,000"
>
> def commafy(s):
> s = s.reverse()
> terms = []
> for i in range(0, len(s), 3):
> terms.append(s[i:i+3])
> return ",".join(terms).reverse()
Hmmm... I think we can walk backwards almost as easily as forwards:
def commaficate(s):
t = []
for i in range(0, len(s), 3):
t.insert(0,s[-3-i:len(s)-i])
return ','.join(t)
Nope, no need for s.reverse() at all, at all here. :-)
>>> s = '1234567890'
>>> for i in range(len(s)):
... print '%s -> %s' % (s[:i], commaficate(s[:i]))
...
->
1 -> 1
12 -> 12
123 -> 123
1234 -> 1,234
12345 -> 12,345
123456 -> 123,456
1234567 -> 1,234,567
12345678 -> 12,345,678
123456789 -> 123,456,789
I suppose it ought to raise a range error exception if there's a period
in the argument, but that's not any different than the reverse()
version...
> - for sequence analysis, compute the "reverse complement" of a sequence.
> That's the sequence used for the other side of the DNA helix from the
> current sequence, eg, so that "aatccgatcg" -> "cgatcggatt"
Whyever do they want it backwards? That's much more interesting, IMO,
than the trivial computation involved!
More information about the Python-list
mailing list