【问题标题】:Is it possible to mix elegantly f-strings with locale.format in Python 3.6是否可以在 Python 3.6 中优雅地将 f-strings 与 locale.format 混合
【发布时间】:2017-08-03 18:22:52
【问题描述】:

Python 3.6(又名 PEP 498)引入了我喜欢的格式化字符串。在某些情况下,我们必须输出用户难以阅读的大量数字。我在下面的示例中使用了区域设置分组。我想知道是否有更好的方法来格式化格式化字符串中的大量数字?

import locale
locale.setlocale(locale.LC_ALL, 'en_US')
count = 80984932412380
s = f'Total count is:{locale.format("%d", count, grouping = True)}'
>>> s
'Total count is:80,984,932,412,380'

非常感谢您的帮助!

【问题讨论】:

    标签: python string formatting python-3.6


    【解决方案1】:

    可以使用库 babel 作为语言环境的线程安全替代方案:

    from babel.numbers import format_decimal
    count = 80984932412380
    
    s = f'Total count is: {format_decimal(count, locale="en_US")}'
    >>> s
    'Total count is: 80,984,932,412,380'
    

    如果你喜欢更短的 f 字符串,你可以定义一个自定义函数:

    def number(x):
        return format_decimal(x, locale="en_US")
    
    f'Total count is: {number(count)}'
    >>> s
    'Total count is: 80,984,932,412,380'
    

    【讨论】:

      【解决方案2】:

      这是一个偏好问题。代码确实与使用较多的字符串格式方法没有区别。这也可以让我更具可读性。

      import locale
      locale.setlocale(locale.LC_ALL, 'en_US')
      count = 80984932412380
      s = 'Total count is: {}'.format(locale.format("%d",count))
      

      【讨论】:

        【解决方案3】:

        语言环境模块有点笨拙,但是一个函数可以很好地包装它:

        import locale
        
        locale.setlocale(locale.LC_ALL, '')
        
        def format_num(value, spec='%d'):
            return locale.format_string(spec, value, grouping=True)
        
        
        count = 80984932412380
        
        >>> f'Total count is: {format_num(count)}.'
        'Total count is: 80,984,932,412,380.'
        

        【讨论】:

          猜你喜欢
          • 2017-04-19
          • 2018-09-22
          • 1970-01-01
          • 1970-01-01
          • 2012-07-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-08-24
          相关资源
          最近更新 更多