将数字转换为字符串时,使用“ {}”。format()删除前导零吗?

时间:2019-07-25 07:11:09

标签: python string format

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

some_number = 0.314
string = '{x}'.format(some_number)

给出输出string '.314'.。任务是:找到x。

当然可以用lstrip来做到这一点,例如heresimilar here

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

,但我认为仅使用 '{ }'.format()方法会更方便。由于我可以将其用于其他格式设置选项,因此有选择地调用lstrip需要额外的代码行。

3 个答案:

答案 0 :(得分:0)

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

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

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

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

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

答案 1 :(得分:0)

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

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

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

答案 2 :(得分:0)

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