From 01eb6934ef2f253ebfa3ea456030e1e3df1abf31 Mon Sep 17 00:00:00 2001 From: Jeremy Fincher Date: Wed, 20 Aug 2003 09:24:57 +0000 Subject: [PATCH] Added function commaAndify to turn a list of strings into a proper English foo, bar, and baz string. --- src/utils.py | 15 +++++++++++++-- test/test_utils.py | 17 +++++++++++++---- 2 files changed, 26 insertions(+), 6 deletions(-) diff --git a/src/utils.py b/src/utils.py index 1434969ee..e98ad78bd 100755 --- a/src/utils.py +++ b/src/utils.py @@ -165,7 +165,7 @@ def timeElapsed(elapsed, leadingZeroes=False, years=True, weeks=True, return ret[0] else: return ' and '.join([', '.join(ret[:-1]), ret[-1]]) - + def distance(s, t): """Returns the levenshtein edit distance between two strings.""" n = len(s) @@ -230,7 +230,7 @@ def perlReToPythonRe(s): except AttributeError: raise ValueError, 'Invalid flag: %s' % c return re.compile(regexp, flag) - + def perlReToReplacer(s): """Converts a string representation of a Perl regular expression (i.e., s/foo/bar/g or s/foo/bar/i) to a Python function doing the equivalent @@ -259,4 +259,15 @@ def findBinaryInPath(s): break return cmdLine +def commaAndify(L): + if len(L) == 0: + return '' + elif len(L) == 1: + return L[0] + elif len(L) == 2: + return '%s and %s' % (L[0], L[1]) + else: + L[-1] = 'and %s' % L[-1] + return ', '.join(L) + # vim:set shiftwidth=4 tabstop=8 expandtab textwidth=78: diff --git a/test/test_utils.py b/test/test_utils.py index 59da86b44..474635f8b 100644 --- a/test/test_utils.py +++ b/test/test_utils.py @@ -104,7 +104,7 @@ class UtilsTest(unittest.TestCase): r = utils.dqrepr(s) self.assertEqual(s, eval(r), s) self.failUnless(r[0] == '"' and r[-1] == '"', s) - + def testPerlReToPythonRe(self): r = utils.perlReToPythonRe('m/foo/') self.failUnless(r.search('foo')) @@ -126,10 +126,19 @@ class UtilsTest(unittest.TestCase): self.assertEqual(f('foobarbaz'), 'foorz') f = utils.perlReToReplacer('s/ba\\///g') self.assertEqual(f('fooba/rba/z'), 'foorz') - + def testFindBinaryInPath(self): - self.assertEqual(None, utils.findBinaryInPath('asdfhjklasdfhjkl')) - self.assertEqual('/bin/sh', utils.findBinaryInPath('sh')) + if os.name == 'posix': + self.assertEqual(None, utils.findBinaryInPath('asdfhjklasdfhjkl')) + self.assertEqual('/bin/sh', utils.findBinaryInPath('sh')) + + def testCommaAndify(self): + L = ['foo'] + self.assertEqual(utils.commaAndify(L), 'foo') + L.append('bar') + self.assertEqual(utils.commaAndify(L), 'foo and bar') + L.append('baz') + self.assertEqual(utils.commaAndify(L), 'foo, bar, and baz') # vim:set shiftwidth=4 tabstop=8 expandtab textwidth=78: