Skip to content

Commit

Permalink
Add support for sign specifiers in number formats. (#134)
Browse files Browse the repository at this point in the history
  • Loading branch information
anntzer authored Mar 22, 2021
1 parent 5bc22a4 commit 0477aa5
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 3 deletions.
5 changes: 3 additions & 2 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ format specification might have been used.

Most of `format()`'s `Format Specification Mini-Language`_ is supported:

[[fill]align][0][width][.precision][type]
[[fill]align][sign][0][width][.precision][type]

The differences between `parse()` and `format()` are:

Expand All @@ -143,7 +143,8 @@ The differences between `parse()` and `format()` are:
That is, the "#" format character is handled automatically by d, b, o
and x formats. For "d" any will be accepted, but for the others the correct
prefix must be present if at all.
- Numeric sign is handled automatically.
- Numeric sign is handled automatically. A sign specifier can be given, but
has no effect.
- The thousands separator is handled automatically if the "n" type is used.
- The types supported are a slightly different mix to the format() types. Some
format() types come directly over: "d", "n", "%", "f", "e", "b", "o" and "x".
Expand Down
5 changes: 4 additions & 1 deletion parse.py
Original file line number Diff line number Diff line change
Expand Up @@ -758,7 +758,7 @@ class RepeatedNameError(ValueError):


def extract_format(format, extra_types):
"""Pull apart the format [[fill]align][0][width][.precision][type]"""
"""Pull apart the format [[fill]align][sign][0][width][.precision][type]"""
fill = align = None
if format[0] in '<>=^':
align = format[0]
Expand All @@ -768,6 +768,9 @@ def extract_format(format, extra_types):
align = format[1]
format = format[2:]

if format.startswith(('+', '-', ' ')):
format = format[1:]

zero = False
if format and format[0] == '0':
zero = True
Expand Down
11 changes: 11 additions & 0 deletions test_parse.py
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,17 @@ def test_typed(self):
r = parse.parse('hello {:w} {:w}', 'hello 12 people')
self.assertEqual(r.fixed, ('12', 'people'))

def test_sign(self):
# sign is ignored
r = parse.parse('Pi = {:.7f}', 'Pi = 3.1415926')
self.assertEqual(r.fixed, (3.1415926,))
r = parse.parse('Pi = {:+.7f}', 'Pi = 3.1415926')
self.assertEqual(r.fixed, (3.1415926,))
r = parse.parse('Pi = {:-.7f}', 'Pi = 3.1415926')
self.assertEqual(r.fixed, (3.1415926,))
r = parse.parse('Pi = {: .7f}', 'Pi = 3.1415926')
self.assertEqual(r.fixed, (3.1415926,))

def test_precision(self):
# pull a float out of a string
r = parse.parse('Pi = {:.7f}', 'Pi = 3.1415926')
Expand Down

0 comments on commit 0477aa5

Please sign in to comment.