结合固定和区域设置符号进行字符串格式化

Combine fixed and locale notation for string formatting

我正在尝试使用 Python's string format mini-language 定义格式字符串,以便获得带有固定表示法但带有本地小数点分隔符的数字的字符串。有关所需输出的进一步说明,请参阅以下代码段:

import locale
import os

if os.name == 'nt':
    locale.setlocale(locale.LC_ALL, 'de-de')    
else:
    locale.setlocale(locale.LC_ALL, 'de_de')

number = 1.234567
print('fixed notation:   {:.7f}'.format(number))
print('general notation: {:.7g}'.format(number))
print('local format:     {:.7n}'.format(number))

desired_output = '{:.7f}'.format(number)
print('desired output:   {}'.format(desired_output.replace('.', ',')))

使用 'regular' 字符串时,将 . 替换为 , 是一个合适的解决方法。但是,这在我的情况下似乎不可行,因为我需要指定 matplotlib.ticker.StrMethodFormatter 以获得所需的输出作为刻度标签。使用语言环境符号按预期工作:

ax.yaxis.set_major_formatter(ticker.StrMethodFormatter('{x:1.3n}'))

不幸的是,我无法找到固定格式(例如 {:.3f})和区域设置符号({:.3n})的组合格式的格式字符串,以启用尾随零填充相同的十进制长度。

正如您在我的示例图中看到的,它们应该具有相等数量的小数位数(可以通过定点符号 '{:.7f}' 来确保)和局部小数分隔符(可以通过 [= 来确保) 18=]):

如果您有一个函数 returns 一个所需格式的字符串,您可以使用此函数通过 FuncFormatter 格式化您的刻度标签。在这种情况下,

func = lambda x,pos: '{:.7f}'.format(x).replace('.', ',')
ax.yaxis.set_major_formatter(mticker.FuncFormatter(func))

这当然与语言环境无关。

我不知道是否可以将语言环境与格式化迷你语言一起使用,但可以扩展上面的相同方法以使用实际语言环境

func2 = lambda x,pos: locale.format('%.7f', x, grouping = True)

在这两种情况下,结果应该相似,类似于