lists.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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-2021 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, style='standard', locale=DEFAULT_LOCALE):
  16. """
  17. Format the items in `lst` as a list.
  18. >>> format_list(['apples', 'oranges', 'pears'], locale='en')
  19. u'apples, oranges, and pears'
  20. >>> format_list(['apples', 'oranges', 'pears'], locale='zh')
  21. u'apples\u3001oranges\u548cpears'
  22. >>> format_list(['omena', 'peruna', 'aplari'], style='or', locale='fi')
  23. u'omena, peruna tai aplari'
  24. These styles are defined, but not all are necessarily available in all locales.
  25. The following text is verbatim from the Unicode TR35-49 spec [1].
  26. * standard:
  27. A typical 'and' list for arbitrary placeholders.
  28. eg. "January, February, and March"
  29. * standard-short:
  30. A short version of a 'and' list, suitable for use with short or abbreviated placeholder values.
  31. eg. "Jan., Feb., and Mar."
  32. * or:
  33. A typical 'or' list for arbitrary placeholders.
  34. eg. "January, February, or March"
  35. * or-short:
  36. A short version of an 'or' list.
  37. eg. "Jan., Feb., or Mar."
  38. * unit:
  39. A list suitable for wide units.
  40. eg. "3 feet, 7 inches"
  41. * unit-short:
  42. A list suitable for short units
  43. eg. "3 ft, 7 in"
  44. * unit-narrow:
  45. A list suitable for narrow units, where space on the screen is very limited.
  46. eg. "3′ 7″"
  47. [1]: https://www.unicode.org/reports/tr35/tr35-49/tr35-general.html#ListPatterns
  48. :param lst: a sequence of items to format in to a list
  49. :param style: the style to format the list with. See above for description.
  50. :param locale: the locale
  51. """
  52. locale = Locale.parse(locale)
  53. if not lst:
  54. return ''
  55. if len(lst) == 1:
  56. return lst[0]
  57. if style not in locale.list_patterns:
  58. raise ValueError('Locale %s does not support list formatting style %r (supported are %s)' % (
  59. locale,
  60. style,
  61. list(sorted(locale.list_patterns)),
  62. ))
  63. patterns = locale.list_patterns[style]
  64. if len(lst) == 2:
  65. return patterns['2'].format(*lst)
  66. result = patterns['start'].format(lst[0], lst[1])
  67. for elem in lst[2:-1]:
  68. result = patterns['middle'].format(result, elem)
  69. result = patterns['end'].format(result, lst[-1])
  70. return result