简体   繁体   English

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

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

Update: as up to now (2019-09), masking leading or trailing zeros in decimal numbers formatted to string seems to be unsupported in Python. 更新:截至目前(2019-09),Python似乎不支持屏蔽格式化为字符串的十进制数字中的前导或尾随零。 You will need to use a workaround to get something like '.01' from the number 0.0101 (assuming 3 decimal places desired). 您将需要使用一种解决方法来从数字0.0101中获取类似“ .01”的值(假设需要3个小数位)。

I would even argue that it's a good thing not to support such a format since 我什至认为, 支持这种格式是一件好事,因为

  • I'd consider '0.01' be better in terms of readability than '.01' 我认为在可读性方面,“ 0.01”比“ .01”更好
  • '0.010' carries information (3 digits of precision...) that is lost in '0.01' '0.010'包含在'0.01'中丢失的信息(精度为3位...)

If desired anyway, one could use one of the suggestions below. 无论如何,如果需要,可以使用以下建议之一。 Thank you all for contributing. 谢谢大家的贡献。

Q: I'm looking for a way to output floating point numbers as strings, formatted without leading/trailing zeros . 问:我正在寻找一种将浮点数输出为字符串的方式,其格式不带前导/尾随零 Is there a way to do this with '{ }'.format() or f-string? 有没有办法用'{ }'.format()或f-string来做到这一点? I searched the internet but didn't find anything. 我搜索了互联网,但没有找到任何东西。 Did I just miss it or is it not possible (Python 3.7)? 我只是想念它还是不可能(Python 3.7)? What I have in mind is basically 我的想法基本上是

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

that gives the output string '.314'. 给出输出string '.314'. . So is there an x that does this? 那么有x可以做到吗?

Of course one could work-around with lstrip / rstrip as described eg here or similar here : 当然,可以使用lstrip / rstrip解决lstrip rstrip ,例如此处所述此处类似

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

but it would be more convenient to use only an f-string. 但是使用f字符串会更方便。 Since I can use that for other formatting options, optionally calling strip demands additional lines of code. 由于我可以将其用于其他格式设置选项,因此可选地调用strip需要额外的代码行。

if you want to just strip 0 from floating numbers you could use this "hack" 如果您只想从浮点数中去除0,则可以使用此“ hack”

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

this is in no way an elegant solution, but it will get the job done 这绝不是一个优雅的解决方案,但它将完成工作

also if you want to use .format as well you don't need another line, you could just 另外,如果您也想使用.format,则不需要另一行,您可以

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

If you want to use format() , then try as below. 如果要使用format() ,请尝试以下操作。

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

Just use lstrip() within format function, you don't need to write additional line of code. 只需在format函数内使用lstrip() ,就无需编写其他代码。

here's a helper function that I came up with since the strip workaround can't be avoided: 这是我想出的一个辅助函数,因为无法避免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