how to improve this simple block of code
Peter Hansen
peter at engcorp.com
Wed Jan 11 13:43:52 EST 2006
py wrote:
> hanz wrote:
>>x = x.rstrip('0.') # removes trailing zeroes and dots
>
> knew there had to be a way, thanks.
But that's not it. :-)
This is a wonderful opportunity for you to learn about unit testing, and
begin the long process of developing good testing habits. Of all the
ideas posted, I believe only Mark Hammond's would correctly pass the
basic obvious test cases, and I don't think anyone (without actually
having checked with tests) should be saying even his is clearly correct.
import unittest
from yourmodule import stripZeros # or whatever you have
class Tests(unittest.TestCase):
def test01(self):
'check zero-stripper'
for input, expected in [
('', ''),
('0', '0'),
('0.0', '0'),
('0.', '0'),
('000.', '000'),
('10', '10'),
('10.0', '10'),
('foo', 'foo'),
('foo.', 'foo'), # ??
('132.15', '132.15'),
('132.60', '132.6'),
('132.00', '132'),
('132.00000', '132'),
('132.000001', '132.000001'),
# add others to taste
]:
self.assertEquals(expected, stripZeros(input))
unittest.main()
Change the above test cases to match what you really want if they're not
correct, then run the script and make sure everything passes.
-Peter
More information about the Python-list
mailing list