python - 如何屏蔽我的 float ,最好不使用正则表达式?

标签 python regex format string-formatting mask

如何使用掩码将 float 格式化为字符串?

(我不精通正则表达式,但如果有人知道单行解决方案,为什么不呢?)

这是我的问题:

我有一个像“6.88”这样的 float ,我需要使用以下掩码“00000000000.00”对其进行格式化

6.88 = "00000000006.88"

14.3 = "00000000014.30"

00.0 = "00000000000.00"

我已经阅读了以下帖子,但我无法理解:

Format number number with specific mask regex python

我的数据示例:

6.88  => 00000000006.88
56.62 => 00000000056.62
9.58  => 00000000009.58
24.75 => 00000000024.75
14.30 => 00000000014.30

我的解决方案不是那么高效也不是那么快:

  1. 将float转换为str
  2. 使用分隔符“.”拆分我的字符串
  3. 统计“.”前后的字符数
  4. 使用这些参数的长度使我的 split[0] 和 split[1] 适应掩码
  5. 完成

有更简单的方法吗?

最佳答案

你会使用 string formatting :

In [21]: '{:014.2f}'.format(6.88)
Out[21]: '00000000006.88'

In [22]: '{:014.2f}'.format(14.30)
Out[22]: '00000000014.30'

In [23]: '{:014.2f}'.format(0)
Out[23]: '00000000000.00'

根据 6.1.3.1. Format Specification Mini-Language ,

  • 0为填充符

  • .2 设置精度为 2

  • 14为结果字符串的宽度

关于python - 如何屏蔽我的 float ,最好不使用正则表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33635792/

相关文章:

python - keras CNN 相同的输出

python - 安全的 Python Markdown 库

python - struct.calcsize (python) 实际计算什么?

mysql格式化mysql结果满足json handsontable

java - 使用 printf 方法显示小数位

python - ScrollBar QStyleSheet 显示时带有背景 它应该是透明的

PHP 正则表达式主题标签和特殊字符

javascript - 针对空格的正则表达式

C fscanf 复杂格式

python - 相当于断言正则表达式 Python 中否定查找中的 (.*)