我正在尝试使用 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('.', ',')))
使用“常规”字符串时,将 .
替换为 ,
是一个合适的解决方法。但是,这在我的情况下似乎不可行,因为我需要指定 matplotlib.ticker.StrMethodFormatter
来获取所需的输出作为刻度标签。使用区域设置符号可以按预期工作:
ax.yaxis.set_major_formatter(ticker.StrMethodFormatter('{x:1.3n}'))
不幸的是,我无法找到固定格式(例如 {:.3f}
)和区域设置符号({:.3n}
)组合格式的格式字符串>) 启用尾随零填充相同的十进制长度。
正如您在我的示例图中看到的,它们应该具有相同数量的小数位数(这可以通过定点表示法 '{:.7f}'
来确保)和本地小数分隔符 (这可以通过 '{:.7n}'
来确保:
最佳答案
如果您有一个函数可以返回所需格式的字符串,您可以使用此函数通过 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)
在这两种情况下,结果应该相似,类似于
关于python - 结合固定和区域设置表示法进行字符串格式化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51503539/