【问题标题】:Number to string conversion with f-string without leading or trailing zeros?使用不带前导零或尾随零的 f 字符串将数字转换为字符串?
【发布时间】:2019-12-03 09:24:24
【问题描述】:

更新: 到目前为止(2019-09),在格式化为字符串的十进制数字中屏蔽前导或尾随零似乎不受支持 Python。您将需要使用解决方法来获得类似“.01”的内容 从数字 0.0101(假设需要 3 个小数位)。

我什至认为支持这种格式是件好事不是 因为

  • 我认为 '0.01' 在可读性方面比 '.01' 更好
  • '0.010' 携带在 '0.01' 中丢失的信息(3 位精度...)

如果需要,可以使用以下建议之一。感谢大家的贡献。

问:我正在寻找一种将浮点数输出为字符串的方法,格式为没有前导/尾随零。有没有办法用'{ }'.format() 或 f-string 做到这一点?我搜索了互联网,但没有找到任何东西。我只是错过了它还是不可能(Python 3.7)? 我的想法基本上是

some_number = 0.3140
string = f'{some_number:x}' # giving '.314'

给出输出string '.314'.。那么有没有 x 可以做到这一点?

当然,可以使用lstrip / rstrip 解决方法,例如描述heresimilar here:

In [93]: str(0.3140).lstrip('0').rstrip('0')
Out[93]: '.314'

但是使用 only 一个 f-string 会更方便。由于我可以将其用于其他格式选项,因此可选地调用 strip 需要额外的代码行。

【问题讨论】:

标签: python string format f-string


【解决方案1】:

如果你只想从浮点数中去掉 0,你可以使用这个“hack”

"." + str(0.314).split("0.")[-1]

这绝不是一个优雅的解决方案,但它会完成工作

如果你也想使用 .format 并且不需要另一行,你可以

"." +str(0.314).split("0.")[-1].format('')

【讨论】:

  • 对不起,我觉得我的问题有点不清楚。我进行了编辑以澄清。
  • 我理解你的问题,试试我上面说的,你会达到你想要的,试试看string = "." + str(some_number).split("0.")[-1]
  • 你的 hack 有效,虽然我认为 lstrip 在代码可读性方面更清晰 - 但问题是:如何使用 '{ }'.format() 实现它
【解决方案2】:

如果您想使用format(),请尝试如下。

print("Hello {0}, your balance is {1}.".format("Adam", "0.314".lstrip('0')))

只需在format函数中使用lstrip()即可,无需多写一行代码。

【讨论】:

  • 这是关于如何仅使用'{}'.format(),即你放在花括号中的内容。正如我在问题中所说,“找到 x”以获得'{x}'.format(0.314) == '.314'。此外,输入是数字类型,而不是字符串。
【解决方案3】:

这是我想出的一个辅助函数,因为strip 解决方法无法避免:

def dec2string_stripped(num, dec_places=3, strip='right'):
    """
    Parameters
    ----------
    num : float or list of float
        scalar or list of decimal numbers.
    dec_places : int, optional
        number of decimal places to return. defaults to 3.
    strip : string, optional
        what to strip. 'right' (default), 'left' or 'both'.

    Returns
    -------
    list of string.
        numbers formatted as strings according to specification (see kwargs).
    """
    if not isinstance(num, list): # might be scalar or numpy array
        try:
            num = list(num)
        except TypeError: # input was scalar
            num = [num]

    if not isinstance(dec_places, int) or int(dec_places) < 1:
        raise ValueError(f"kwarg dec_places must be integer > 1 (got {dec_places})")

    if strip == 'right':
        return [f"{n:.{str(dec_places)}f}".rstrip('0') for n in num]
    if strip == 'left':
        return [f"{n:.{str(dec_places)}f}".lstrip('0') for n in num]
    if strip == 'both':
        return [f"{n:.{str(dec_places)}f}".strip('0') for n in num]
    raise ValueError(f"kwarg 'strip' must be 'right', 'left' or 'both' (got '{strip}')")

【讨论】:

    【解决方案4】:

    只是在这里提一下...如果您使用numpy,还有np.format_float_positional() 功能可以让您完全控制如何将数字显示为字符串并修剪尾随零...

    来自np.format_float_positional的文档:

    将浮点标量格式化为位置表示法的十进制字符串。

    提供对舍入、修剪和填充的控制。使用并假设 IEEE >无偏舍入。使用“Dragon4”算法。

    去掉前导零只是一个简单的检查,我们是否正在处理一个以 0 开头的数字

    import numpy as np
    def format_float(x, trim_leading=True, **kwargs):
        s = np.format_float_positional(x, **kwargs)
        if trim_leading is True and int(x) == 0 and len(s) > 1:
            s = s.replace("0.", ".")
        return s
    
    format_float(0.0234001232, trim_leading=True, precision=4)
    >>> '.0234'
    format_float(0.0234001232, trim_leading=False, precision=4)
    >>> '0.0234'
    format_float(0.0234001232, precision=8)
    >>> '0.02340012'
    format_float(12.000558, precision=2, trim="-", fractional=False)
    >>> '12'
    

    【讨论】:

      猜你喜欢
      • 2022-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-25
      • 2014-08-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多