zeropad.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import unittest
  2. import re
  3. class SimpleTestCase(unittest.TestCase):
  4. def setUp(self):
  5. '''
  6. Init object
  7. '''
  8. self.__rightPad = RightPad()
  9. def testConvert(self):
  10. usecases = [
  11. [ 12, '12.00' ] ,
  12. [ 12.1, '12.10' ],
  13. [ 12.11, '12.11' ],
  14. [ 12.12052, '12.12']
  15. ]
  16. for usecase in usecases:
  17. self.assertEqual(self.__rightPad.convert(usecase[0]), usecase[1])
  18. class RightPad(object):
  19. def __init__(self, limit = 2):
  20. self.__limit = limit
  21. def convert(self, rawValue):
  22. # turn value into a string
  23. stringValue = str(rawValue)
  24. # Apply regex on it
  25. p = re.compile(r'^(\d+\.\d{%d})$|^(\d+)(\.\d*)?$'%(self.__limit))
  26. matches = re.search(p, stringValue)
  27. #no treatment required
  28. if (matches.lastindex == 1) :
  29. print("A")
  30. return stringValue
  31. #Only pad an integer
  32. elif (matches.lastindex == 2) :
  33. print("B")
  34. return matches.group(2) + '.' + '0'*self.__limit
  35. #either pad float value or truncate it to fit limit
  36. elif (matches.lastindex == 3) :
  37. print("C")
  38. group = str(matches.group(3))
  39. #truncate value
  40. if (len(group) > self.__limit):
  41. return matches.group(2) + group[:self.__limit + 1]
  42. #pad value
  43. else:
  44. return matches.group(2) + matches.group(3) + "0"*(self.__limit - len(group) + 1)
  45. return 'Fly you fool!'
  46. if __name__ == "__main__":
  47. unittest.main() # run all tests