From 348e90f3756f0ce75ef746a2bbc4c4a7c8a1c47d 2013-10-07 12:43:32 From: Martín Gaitán Date: 2013-10-07 12:43:32 Subject: [PATCH] adding get_text_list helper inspired in django's one --- diff --git a/IPython/utils/text.py b/IPython/utils/text.py index 2980e0e..38221ed 100644 --- a/IPython/utils/text.py +++ b/IPython/utils/text.py @@ -724,3 +724,32 @@ def columnize(items, separator=' ', displaywidth=80): fmatrix = [filter(None, x) for x in matrix] sjoin = lambda x : separator.join([ y.ljust(w, ' ') for y, w in zip(x, info['columns_width'])]) return '\n'.join(map(sjoin, fmatrix))+'\n' + + +def get_text_list(list_, last_word='and', wrap_item_with=""): + """ + Return a string with a natural enumeration of items + + >>> get_text_list(['a', 'b', 'c', 'd']) + 'a, b, c and d' + >>> get_text_list(['a', 'b', 'c'], 'or') + 'a, b or c' + >>> get_text_list(['a', 'b'], 'or') + 'a or b' + >>> get_text_list(['a']) + 'a' + >>> get_text_list([]) + '' + >>> get_text_list(['a', 'b'], wrap_item_with="`") + '`a` and `b`' + """ + if len(list_) == 0: + return '' + if wrap_item_with: + list_ = ['%s%s%s' % (wrap_item_with, item, wrap_item_with) for + item in list_] + if len(list_) == 1: + return list_[0] + return '%s %s %s' % ( + ', '.join(i for i in list_[:-1]), + last_word, list_[-1]) \ No newline at end of file