add separator param

This commit is contained in:
InspectorCaracal 2022-06-28 15:52:23 -06:00
parent 2e3ce55fce
commit a957417c79
2 changed files with 8 additions and 5 deletions

View file

@ -57,13 +57,15 @@ class TestDedent(TestCase):
class TestListToString(TestCase):
"""
Default function header from utils.py:
list_to_string(inlist, endsep=", and", addquote=False)
list_to_string(inlist, sep=",", endsep=", and", addquote=False)
Examples:
with default endsep:
with defaults:
[1,2,3] -> '1, 2, and 3'
with endsep==',':
[1,2,3] -> '1, 2, 3'
with sep==';' and endsep==';':
[1,2,3] -> '1; 2; 3'
with endsep=='and':
[1,2,3] -> '1, 2 and 3'
with addquote and endsep="and"
@ -74,6 +76,7 @@ class TestListToString(TestCase):
self.assertEqual("1, 2, and 3", utils.list_to_string([1, 2, 3]))
self.assertEqual("1, 2, 3", utils.list_to_string([1, 2, 3], endsep=","))
self.assertEqual("1, 2 and 3", utils.list_to_string([1, 2, 3], endsep="and"))
self.assertEqual("1; 2; 3", utils.list_to_string([1, 2, 3], sep=";", endsep=";"))
self.assertEqual('"1", "2", "3"', utils.list_to_string([1, 2, 3], endsep=",", addquote=True))
self.assertEqual(
'"1", "2" and "3"', utils.list_to_string([1, 2, 3], endsep="and", addquote=True)

View file

@ -362,7 +362,7 @@ def columnize(string, columns=2, spacing=4, align="l", width=None):
return "\n".join(rows)
def iter_to_str(iterable, endsep=", and", addquote=False):
def iter_to_str(iterable, sep=",", endsep=", and", addquote=False):
"""
This pretty-formats an iterable list as string output, adding an optional
alternative separator to the second to last entry. If `addquote`
@ -404,7 +404,7 @@ def iter_to_str(iterable, endsep=", and", addquote=False):
else:
iterable = tuple(str(val) for val in iterable)
if endsep.startswith(","):
if endsep.startswith(sep):
# oxford comma alternative
endsep = endsep[1:] if len_iter < 3 else endsep
elif endsep:
@ -416,7 +416,7 @@ def iter_to_str(iterable, endsep=", and", addquote=False):
elif len_iter == 2:
return f"{endsep} ".join(str(v) for v in iterable)
else:
return ", ".join(str(v) for v in iterable[:-1]) + f"{endsep} {iterable[-1]}"
return f"{sep} ".join(str(v) for v in iterable[:-1]) + f"{endsep} {iterable[-1]}"
# legacy aliases