使用f字符串将数字转换为字符串而没有前导或尾随零? [英] Number to string conversion with f-string without leading or trailing zeros?

查看:119
本文介绍了使用f字符串将数字转换为字符串而没有前导或尾随零?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更新:到目前为止(2019-09年),似乎不支持在格式为字符串的十进制数字中屏蔽前导或尾随零. Python.您将需要使用变通方法来获得类似".01"的信息 从数字0.0101开始(假设需要保留3个小数位).

Update: as up to now (2019-09), masking leading or trailing zeros in decimal numbers formatted to string seems to be unsupported in Python. You will need to use a workaround to get something like '.01' from the number 0.0101 (assuming 3 decimal places desired).

我什至认为支持这种格式是一件好事 自

I would even argue that it's a good thing not to support such a format since

  • 在可读性方面,我认为"0.01"比".01"要好
  • '0.010'包含丢失在'0.01'中的信息(精度为3位...)

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

If desired anyway, one could use one of the suggestions below. Thank you all for contributing.

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

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? I searched the internet but didn't find anything. Did I just miss it or is it not possible (Python 3.7)? What I have in mind is basically

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

给出输出string '.314'.

.那么,有没有x可以做到这一点?

that gives the output string '.314'.. So is there an x that does this?

当然可以使用lstrip/rstrip解决,例如此处

Of course one could work-around with lstrip / rstrip as described e.g. here or similar here:

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

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

but it would be more convenient to use only an f-string. Since I can use that for other formatting options, optionally calling strip demands additional lines of code.

推荐答案

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

here's a helper function that I came up with since the strip workaround can't be avoided:

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}')")

这篇关于使用f字符串将数字转换为字符串而没有前导或尾随零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆