string_format2.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. # comprehensive functionality test for {} format string
  2. int_tests = False # these take a while
  3. char_tests = True
  4. str_tests = True
  5. def test(fmt, *args):
  6. print('{:8s}'.format(fmt) + '>' + fmt.format(*args) + '<')
  7. def test_fmt(conv, fill, alignment, sign, prefix, width, precision, type, arg):
  8. fmt = '{'
  9. if conv:
  10. fmt += '!'
  11. fmt += conv
  12. fmt += ':'
  13. if alignment:
  14. fmt += fill
  15. fmt += alignment
  16. fmt += sign
  17. fmt += prefix
  18. fmt += width
  19. if precision:
  20. fmt += '.'
  21. fmt += precision
  22. fmt += type
  23. fmt += '}'
  24. test(fmt, arg)
  25. if fill == '0' and alignment == '=':
  26. fmt = '{:'
  27. fmt += sign
  28. fmt += prefix
  29. fmt += width
  30. if precision:
  31. fmt += '.'
  32. fmt += precision
  33. fmt += type
  34. fmt += '}'
  35. test(fmt, arg)
  36. if int_tests:
  37. int_nums = (-1234, -123, -12, -1, 0, 1, 12, 123, 1234, True, False)
  38. #int_nums = (-12, -1, 0, 1, 12, True, False)
  39. for type in ('', 'b', 'd', 'o', 'x', 'X'):
  40. for width in ('', '1', '3', '5', '7'):
  41. for alignment in ('', '<', '>', '=', '^'):
  42. for fill in ('', ' ', '0', '@'):
  43. for sign in ('', '+', '-', ' '):
  44. for prefix in ('', '#'):
  45. for num in int_nums:
  46. test_fmt('', fill, alignment, sign, prefix, width, '', type, num)
  47. if char_tests:
  48. for width in ('', '1', '2'):
  49. for alignment in ('', '<', '>', '^'):
  50. for fill in ('', ' ', '0', '@'):
  51. test_fmt('', fill, alignment, '', '', width, '', 'c', 48)
  52. if str_tests:
  53. for conv in ('', 'r', 's'):
  54. for width in ('', '1', '4', '10'):
  55. for alignment in ('', '<', '>', '^'):
  56. for fill in ('', ' ', '0', '@'):
  57. for str in ('', 'a', 'bcd', 'This is a test with a longer string'):
  58. test_fmt(conv, fill, alignment, '', '', width, '', 's', str)