[formatter] add 'q' & 'Q' conversions - URL-en/decode values

This commit is contained in:
Mike Fährmann
2026-02-03 16:29:34 +01:00
parent 5ddee423ed
commit 0be3383110
3 changed files with 20 additions and 1 deletions

View File

@@ -189,6 +189,18 @@ Conversion specifiers allow to *convert* the value to a different form or type.
<td><code>{created!D}</code></td>
<td><code>2010-01-01 00:00:00</code></td>
</tr>
<tr>
<td align="center"><code>q</code></td>
<td><a href="https://docs.python.org/3/library/urllib.parse.html#urllib.parse.quote">URL-encode</a> a value</td>
<td><code>{jpn!q}</code></td>
<td><code>%E6%A3%AE</code></td>
</tr>
<tr>
<td align="center"><code>Q</code></td>
<td><a href="https://docs.python.org/3/library/urllib.parse.html#urllib.parse.unquote">URL-decode</a> a value</td>
<td><code>{jpn_url!Q}</code></td>
<td><code>森</code></td>
</tr>
<tr>
<td align="center"><code>U</code></td>
<td>Convert HTML entities</td>

View File

@@ -606,6 +606,8 @@ _CONVERSIONS = {
"T": dt.to_ts_string,
"d": dt.parse_ts,
"D": dt.convert,
"q": text.quote,
"Q": text.unquote,
"U": text.unescape,
"H": lambda s: text.unescape(text.remove_html(s)),
"g": text.slugify,

View File

@@ -32,6 +32,7 @@ class TestFormatter(unittest.TestCase):
"a": "hElLo wOrLd",
"b": "äöü",
"j": "げんそうきょう",
"J": "%E3%81%92%E3%82%93%E3%81%9D",
"d": {"a": "foo", "b": 0, "c": None},
"i": 2,
"l": ["a", "b", "c"],
@@ -109,9 +110,13 @@ class TestFormatter(unittest.TestCase):
self._run_test("{i_str!i}", 12345)
self._run_test("{i_str!f}", 12345.0)
self._run_test("{f_str!f}", 12.45)
self._run_test("{j!q}", "%E3%81%92%E3%82%93%E3%81%9D"
"%E3%81%86%E3%81%8D%E3%82%87%E3%81%86")
self._run_test("{J!Q}", "げんそ")
# undefined conversion
with self.assertRaises(KeyError):
self._run_test("{a!q}", "hello world")
self._run_test("{a!z}", "hello world")
def test_optional(self):
self._run_test("{name}{title1}", "NameTitle")