lists.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. # -*- coding: utf-8 -*-
  2. """
  3. babel.lists
  4. ~~~~~~~~~~~
  5. Locale dependent formatting of lists.
  6. The default locale for the functions in this module is determined by the
  7. following environment variables, in that order:
  8. * ``LC_ALL``, and
  9. * ``LANG``
  10. :copyright: (c) 2015 by the Babel Team.
  11. :license: BSD, see LICENSE for more details.
  12. """
  13. from babel.core import Locale, default_locale
  14. DEFAULT_LOCALE = default_locale()
  15. def format_list(lst, locale=DEFAULT_LOCALE):
  16. """
  17. Format the items in `lst` as a list.
  18. >>> format_list(['apples', 'oranges', 'pears'], 'en')
  19. u'apples, oranges, and pears'
  20. >>> format_list(['apples', 'oranges', 'pears'], 'zh')
  21. u'apples\u3001oranges\u548cpears'
  22. :param lst: a sequence of items to format in to a list
  23. :param locale: the locale
  24. """
  25. locale = Locale.parse(locale)
  26. if not lst:
  27. return ''
  28. if len(lst) == 1:
  29. return lst[0]
  30. if len(lst) == 2:
  31. return locale.list_patterns['2'].format(*lst)
  32. result = locale.list_patterns['start'].format(lst[0], lst[1])
  33. for elem in lst[2:-1]:
  34. result = locale.list_patterns['middle'].format(result, elem)
  35. result = locale.list_patterns['end'].format(result, lst[-1])
  36. return result