如何将零填充到字符串?

发布于 2022-02-17 09:38:04

什么是 Pythonic 的方法来填充数字字符串的左侧为零,即数字字符串具有特定的长度?

关注者
0
被浏览
37
1 个回答
  • 面试哥
    面试哥 2022-02-17
    为面试而生,有面试问题,就找面试哥。

    字符串:

    >>> n = '4'
    >>> print(n.zfill(3))
    004
    

    对于数字:

    >>> n = 4
    >>> print(f'{n:03}') # Preferred method, python >= 3.6
    004
    >>> print('%03d' % n)
    004
    >>> print(format(n, '03')) # python >= 2.6
    004
    >>> print('{0:03d}'.format(n))  # python >= 2.6 + python 3
    004
    >>> print('{foo:03d}'.format(foo=n))  # python >= 2.6 + python 3
    004
    >>> print('{:03d}'.format(n))  # python >= 2.7 + python3
    004
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看