implement R<old>/<new>/ format option (#318)
This commit is contained in:
@@ -341,6 +341,7 @@ class Formatter():
|
||||
- "c": calls str.capitalize
|
||||
- "C": calls string.capwords
|
||||
- "U": calls urllib.parse.unquote
|
||||
- "S": calls util.to_string()
|
||||
- Example: {f!l} -> "example"; {f!u} -> "EXAMPLE"
|
||||
|
||||
Extra Format Specifiers:
|
||||
@@ -359,6 +360,10 @@ class Formatter():
|
||||
- "J<separator>/":
|
||||
Joins elements of a list (or string) using <separator>
|
||||
Example: {f:J - /} -> "a - b - c" (if "f" is ["a", "b", "c"])
|
||||
|
||||
- "R<old>/<new>/":
|
||||
Replaces all occurrences of <old> with <new>
|
||||
Example: {f:R /_/} -> "f_o_o_b_a_r" (if "f" is "f o o b a r")
|
||||
"""
|
||||
CONVERSIONS = {
|
||||
"l": str.lower,
|
||||
@@ -417,6 +422,8 @@ class Formatter():
|
||||
func = self._format_maxlen
|
||||
elif format_spec[0] == "J":
|
||||
func = self._format_join
|
||||
elif format_spec[0] == "R":
|
||||
func = self._format_replace
|
||||
else:
|
||||
func = self._format_default
|
||||
fmt = func(format_spec)
|
||||
@@ -484,6 +491,15 @@ class Formatter():
|
||||
separator = separator[1:]
|
||||
return wrap
|
||||
|
||||
@staticmethod
|
||||
def _format_replace(format_spec):
|
||||
def wrap(obj):
|
||||
obj = obj.replace(old, new)
|
||||
return format(obj, format_spec)
|
||||
old, new, format_spec = format_spec.split("/", 2)
|
||||
old = old[1:]
|
||||
return wrap
|
||||
|
||||
@staticmethod
|
||||
def _format_default(format_spec):
|
||||
def wrap(obj):
|
||||
|
||||
@@ -27,7 +27,6 @@ TRAVIS_SKIP = {
|
||||
# temporary issues, etc.
|
||||
BROKEN = {
|
||||
"mangapark",
|
||||
"pixnet",
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -264,6 +264,15 @@ class TestFormatter(unittest.TestCase):
|
||||
self._run_test("{a:J/}" , self.kwdict["a"])
|
||||
self._run_test("{a:J, /}" , ", ".join(self.kwdict["a"]))
|
||||
|
||||
def test_replace(self):
|
||||
self._run_test("{a:Rh/C/}" , "CElLo wOrLd")
|
||||
self._run_test("{a!l:Rh/C/}", "Cello world")
|
||||
self._run_test("{a!u:Rh/C/}", "HELLO WORLD")
|
||||
|
||||
self._run_test("{a!l:Rl/_/}", "he__o wor_d")
|
||||
self._run_test("{a!l:Rl//}" , "heo word")
|
||||
self._run_test("{name:Rame/othing/}", "Nothing")
|
||||
|
||||
def _run_test(self, format_string, result, default=None):
|
||||
formatter = util.Formatter(format_string, default)
|
||||
output = formatter.format_map(self.kwdict)
|
||||
|
||||
Reference in New Issue
Block a user