繁体   English   中英

使用f字符串将数字转换为字符串而没有前导或尾随零?

[英]Number to string conversion with f-string without leading or trailing zeros?

更新:截至目前(2019-09),Python似乎不支持屏蔽格式化为字符串的十进制数字中的前导或尾随零。 您将需要使用一种解决方法来从数字0.0101中获取类似“ .01”的值(假设需要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解决lstrip rstrip ,例如此处所述此处类似

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

但是使用f字符串会更方便。 由于我可以将其用于其他格式设置选项,因此可选地调用strip需要额外的代码行。

如果您只想从浮点数中去除0,则可以使用此“ hack”

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

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

另外,如果您也想使用.format,则不需要另一行,您可以

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

如果要使用format() ,请尝试以下操作。

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

只需在format函数内使用lstrip() ,就无需编写其他代码。

这是我想出的一个辅助函数,因为无法避免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}')")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM