implement L<maxlen>/<replacement>/ format option
The L option allows for the contents of a format field to be replaced
with <replacement> if its length is greater than <maxlen>.
Example:
{f:L5/too long/} -> "foo" (if "f" is "foo")
-> "too long" (if "f" is "foobar")
(#92) (#94)
This commit is contained in:
@@ -284,6 +284,12 @@ class Formatter():
|
|||||||
Otherwise the whole replacement field becomes an empty string.
|
Otherwise the whole replacement field becomes an empty string.
|
||||||
Example: {f:?-+/+-/} -> "-+Example+-" (if "f" contains "Example")
|
Example: {f:?-+/+-/} -> "-+Example+-" (if "f" contains "Example")
|
||||||
-> "" (if "f" is None, 0, "")
|
-> "" (if "f" is None, 0, "")
|
||||||
|
|
||||||
|
- "L<maxlen>/<replacement>/":
|
||||||
|
Replaces the output with <replacement> if its length (in characters)
|
||||||
|
exceeds <maxlen>. Otherwise everything is left as is.
|
||||||
|
Example: {f:L5/too long/} -> "foo" (if "f" is "foo")
|
||||||
|
-> "too long" (if "f" is "foobar")
|
||||||
"""
|
"""
|
||||||
conversions = {
|
conversions = {
|
||||||
"l": str.lower,
|
"l": str.lower,
|
||||||
@@ -331,6 +337,11 @@ class Formatter():
|
|||||||
return ""
|
return ""
|
||||||
before, after, format_spec = format_spec.split("/", 2)
|
before, after, format_spec = format_spec.split("/", 2)
|
||||||
return before[1:] + format(value, format_spec) + after
|
return before[1:] + format(value, format_spec) + after
|
||||||
|
if format_spec[0] == "L":
|
||||||
|
maxlen, replacement, format_spec = format_spec.split("/", 2)
|
||||||
|
maxlen = text.parse_int(maxlen[1:])
|
||||||
|
value = format(value, format_spec)
|
||||||
|
return value if len(value) <= maxlen else replacement
|
||||||
return format(value, format_spec)
|
return format(value, format_spec)
|
||||||
|
|
||||||
def get_field(self, field_name, kwargs):
|
def get_field(self, field_name, kwargs):
|
||||||
|
|||||||
@@ -210,6 +210,14 @@ class TestFormatter(unittest.TestCase):
|
|||||||
self._run_test("{a[:50]}", v[:50])
|
self._run_test("{a[:50]}", v[:50])
|
||||||
self._run_test("{a[:]}" , v)
|
self._run_test("{a[:]}" , v)
|
||||||
|
|
||||||
|
def test_maxlen(self):
|
||||||
|
v = self.kwdict["a"]
|
||||||
|
self._run_test("{a:L5/foo/}" , "foo")
|
||||||
|
self._run_test("{a:L50/foo/}", v)
|
||||||
|
self._run_test("{a:L50/foo/>50}", " " * 39 + v)
|
||||||
|
self._run_test("{a:L50/foo/>51}", "foo")
|
||||||
|
self._run_test("{a:Lab/foo/}", "foo")
|
||||||
|
|
||||||
def _run_test(self, format_string, result, default=None):
|
def _run_test(self, format_string, result, default=None):
|
||||||
formatter = util.Formatter(default)
|
formatter = util.Formatter(default)
|
||||||
output = formatter.vformat(format_string, self.kwdict)
|
output = formatter.vformat(format_string, self.kwdict)
|
||||||
|
|||||||
Reference in New Issue
Block a user