Added function commaAndify to turn a list of strings into a proper English foo, bar, and baz string.

This commit is contained in:
Jeremy Fincher 2003-08-20 09:24:57 +00:00
parent 15ba96b4eb
commit 01eb6934ef
2 changed files with 26 additions and 6 deletions

View File

@ -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:

View File

@ -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: