将零填充到字符串的最好方法

1309 python string zero-padding

使用零填充数字字符串的最Pythonic方法是什么,即数字字符串是否具有特定长度?

Har*_*mbe 2162

字符串:

>>> n = '4'
>>> print(n.zfill(3))
004
Run Code Online (Sandbox Code Playgroud)

对于数字:

>>> 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
Run Code Online (Sandbox Code Playgroud)

字符串格式文档.

  • 注释`python> = 2.6`不正确.该语法不适用于`python> = 3`.您可以将其更改为`python <3`,但我可以建议使用括号并完全省略注释(鼓励推荐使用)? (6认同)
  • 请注意,您不需要为格式字符串编号:`'{:03d} {:03d}'.format(1,2)`隐式按顺序分配值. (4认同)
  • [“应该有一种-最好只有一种-显而易见的方法。”](https://www.python.org/dev/peps/pep-0020/),是吗?:) (4认同)
  • 对于'float'类型的对象,未知格式代码'd'. (3认同)
  • 你怎么能没有在你的例子中使用数字 7 呢?!? (3认同)
  • 这些方法中的任何一种都可以适用于可变数量的零吗? (2认同)
  • @AndersRaboThorbeck`“ {n:0 {x} d}”。format(n = 4,x = 3)` (2认同)

Pau*_*den 328

只需使用字符串对象的rjust方法.

此示例将生成一个长度为10个字符的字符串,根据需要填充.

>>> t = 'test'
>>> t.rjust(10, '0')
>>> '000000test'
Run Code Online (Sandbox Code Playgroud)

  • @StanislavKoncebovski 字符串在 Python 中是不可变的。无论您对它做什么,字符串的值都将始终保持不变,并且如果您想更新变量以引用新字符串,则始终必须重新分配。这与rjust无关。 (3认同)

Kon*_*lph 110

对于数字:

print(f'{number:05d}') # (since Python 3.6), or
print('{:05d}'.format(number)) # or
print('{0:05d}'.format(number)) # or (explicit 0th positional arg. selection)
print('{n:05d}'.format(n=number)) # or (explicit `n` keyword arg. selection)
print(format(number, '05d'))
Run Code Online (Sandbox Code Playgroud)

另请参见:Python:字符串格式.

编辑:这是值得注意的是,截至昨日 2008年12月3日,格式化的这种方法有利于被弃用zfill字符串的方法:

print(f'{number:05d}') # (since Python 3.6), or
print('{:05d}'.format(number)) # or
print('{0:05d}'.format(number)) # or (explicit 0th positional arg. selection)
print('{n:05d}'.format(n=number)) # or (explicit `n` keyword arg. selection)
print(format(number, '05d'))
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅PEP 3101.

  • "EDIT"仍然声明"......这种格式化方法已被弃用......". (4认同)
  • PEP 3101未声明%以任何方式被弃用. (3认同)

Cee*_*man 53

适用于Python 2和Python 3:

>>> "{:0>2}".format("1")  # Works for both numbers and strings.
'01'
>>> "{:02}".format(1)  # Works only for numbers.
'01'
Run Code Online (Sandbox Code Playgroud)


Vic*_*tes 51

>>> '99'.zfill(5)
'00099'
>>> '99'.rjust(5,'0')
'00099'
Run Code Online (Sandbox Code Playgroud)

如果你想要相反:

>>> '99'.ljust(5,'0')
'99000'
Run Code Online (Sandbox Code Playgroud)


Joh*_*web 37

str(n).zfill(width)将使用strings,ints,floats ...并且是Python 2. x和3. x兼容:

>>> n = 3
>>> str(n).zfill(5)
'00003'
>>> n = '3'
>>> str(n).zfill(5)
'00003'
>>> n = '3.0'
>>> str(n).zfill(5)
'003.0'
Run Code Online (Sandbox Code Playgroud)


ruo*_*ola 25

使用 Python 时>= 3.6,最简洁的方法是使用带有字符串格式的f字符串

>>> s = f"{1:08}"  # inline with int
>>> s
'00000001'
Run Code Online (Sandbox Code Playgroud)
>>> s = f"{'1':0>8}"  # inline with str
>>> s
'00000001'
Run Code Online (Sandbox Code Playgroud)
>>> n = 1
>>> s = f"{n:08}"  # int variable
>>> s
'00000001'
Run Code Online (Sandbox Code Playgroud)
>>> c = "1"
>>> s = f"{c:0>8}"  # str variable
>>> s
'00000001'
Run Code Online (Sandbox Code Playgroud)

我更喜欢用 格式化int,因为只有这样才能正确处理符号:

>>> f"{-1:08}"
'-0000001'

>>> f"{1:+08}"
'+0000001'

>>> f"{'-1':0>8}"
'000000-1'
Run Code Online (Sandbox Code Playgroud)


ela*_*ver 20

对于那些来这里了解而不仅仅是快速回答的人.我特别为时间字符串做这些:

hour = 4
minute = 3
"{:0>2}:{:0>2}".format(hour,minute)
# prints 04:03

"{:0>3}:{:0>5}".format(hour,minute)
# prints '004:00003'

"{:0<3}:{:0<5}".format(hour,minute)
# prints '400:30000'

"{:$<3}:{:#<5}".format(hour,minute)
# prints '4$$:3####'
Run Code Online (Sandbox Code Playgroud)

"0"符号用"2"填充字符替换什么,默认为空格

">"符号将所有2"0"字符对齐到字符串的左侧

":"符号format_spec


Aar*_*all 18

使用零填充数字字符串的最pythonic方法是什么,即数字字符串是否具有特定长度?

str.zfill 特别打算这样做:

>>> '1'.zfill(4)
'0001'
Run Code Online (Sandbox Code Playgroud)

请注意,它专门用于处理请求的数字字符串,并将a +或移动-到字符串的开头:

>>> '+1'.zfill(4)
'+001'
>>> '-1'.zfill(4)
'-001'
Run Code Online (Sandbox Code Playgroud)

这是帮助str.zfill:

>>> help(str.zfill)
Help on method_descriptor:

zfill(...)
    S.zfill(width) -> str

    Pad a numeric string S with zeros on the left, to fill a field
    of the specified width. The string S is never truncated.
Run Code Online (Sandbox Code Playgroud)

性能

这也是替代方法中性能最高的:

>>> min(timeit.repeat(lambda: '1'.zfill(4)))
0.18824880896136165
>>> min(timeit.repeat(lambda: '1'.rjust(4, '0')))
0.2104538488201797
>>> min(timeit.repeat(lambda: f'{1:04}'))
0.32585487607866526
>>> min(timeit.repeat(lambda: '{:04}'.format(1)))
0.34988890308886766
Run Code Online (Sandbox Code Playgroud)

为了最好地比较该%方法的苹果与苹果(注意它实际上较慢),否则将预先计算:

>>> min(timeit.repeat(lambda: '1'.zfill(0 or 4)))
0.19728074967861176
>>> min(timeit.repeat(lambda: '%04d' % (0 or 1)))
0.2347015216946602
Run Code Online (Sandbox Code Playgroud)

履行

通过一点挖掘,我发现了该zfill方法的实现Objects/stringlib/transmogrify.h:

static PyObject *
stringlib_zfill(PyObject *self, PyObject *args)
{
    Py_ssize_t fill;
    PyObject *s;
    char *p;
    Py_ssize_t width;

    if (!PyArg_ParseTuple(args, "n:zfill", &width))
        return NULL;

    if (STRINGLIB_LEN(self) >= width) {
        return return_self(self);
    }

    fill = width - STRINGLIB_LEN(self);

    s = pad(self, fill, 0, '0');

    if (s == NULL)
        return NULL;

    p = STRINGLIB_STR(s);
    if (p[fill] == '+' || p[fill] == '-') {
        /* move sign to beginning of string */
        p[0] = p[fill];
        p[fill] = '0';
    }

    return s;
}
Run Code Online (Sandbox Code Playgroud)

让我们来看看这个C代码.

它首先在位置上解析参数,这意味着它不允许关键字参数:

>>> '1'.zfill(width=4)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: zfill() takes no keyword arguments
Run Code Online (Sandbox Code Playgroud)

然后检查它是否长度相同或更长,在这种情况下它返回字符串.

>>> '1'.zfill(0)
'1'
Run Code Online (Sandbox Code Playgroud)

zfill调用pad(该pad功能也被称为ljust,rjustcenter也).这基本上将内容复制到一个新字符串并填充填充.

static inline PyObject *
pad(PyObject *self, Py_ssize_t left, Py_ssize_t right, char fill)
{
    PyObject *u;

    if (left < 0)
        left = 0;
    if (right < 0)
        right = 0;

    if (left == 0 && right == 0) {
        return return_self(self);
    }

    u = STRINGLIB_NEW(NULL, left + STRINGLIB_LEN(self) + right);
    if (u) {
        if (left)
            memset(STRINGLIB_STR(u), fill, left);
        memcpy(STRINGLIB_STR(u) + left,
               STRINGLIB_STR(self),
               STRINGLIB_LEN(self));
        if (right)
            memset(STRINGLIB_STR(u) + left + STRINGLIB_LEN(self),
                   fill, right);
    }

    return u;
}
Run Code Online (Sandbox Code Playgroud)

在调用之后pad,zfill移动任何最初的前置+-字符串的开头.

请注意,对于原始字符串实际上是数字不是必需的:

>>> '+foo'.zfill(10)
'+000000foo'
>>> '-foo'.zfill(10)
'-000000foo'
Run Code Online (Sandbox Code Playgroud)


Pet*_*ell 17

width = 10
x = 5
print "%0*d" % (width, x)
> 0000000005
Run Code Online (Sandbox Code Playgroud)

有关所有令人兴奋的细节,请参阅打印文档!

Python 3.x更新(7.5年后)

最后一行现在应该是:

print("%0*d" % (width, x))
Run Code Online (Sandbox Code Playgroud)

print()现在是一个功能,而不是一个声明.请注意,我仍然更喜欢老派printf()风格,因为,IMNSHO,它读起来更好,因为,嗯,我从1980年1月开始使用那种符号.某些东西......老狗......什么东西......新技巧.


小智 11

我正在添加如何从 f 字符串中的字符串长度使用 int ,因为它似乎没有被覆盖:

>>> pad_number = len("this_string")
11
>>> s = f"{1:0{pad_number}}" }
>>> s
'00000000001'

Run Code Online (Sandbox Code Playgroud)


小智 5

对于保存为整数的邮政编码:

>>> a = 6340
>>> b = 90210
>>> print '%05d' % a
06340
>>> print '%05d' % b
90210
Run Code Online (Sandbox Code Playgroud)


Sim*_*ger 5

快速时序比较:

setup = '''
from random import randint
def test_1():
    num = randint(0,1000000)
    return str(num).zfill(7)
def test_2():
    num = randint(0,1000000)
    return format(num, '07')
def test_3():
    num = randint(0,1000000)
    return '{0:07d}'.format(num)
def test_4():
    num = randint(0,1000000)
    return format(num, '07d')
def test_5():
    num = randint(0,1000000)
    return '{:07d}'.format(num)
def test_6():
    num = randint(0,1000000)
    return '{x:07d}'.format(x=num)
def test_7():
    num = randint(0,1000000)
    return str(num).rjust(7, '0')
'''
import timeit
print timeit.Timer("test_1()", setup=setup).repeat(3, 900000)
print timeit.Timer("test_2()", setup=setup).repeat(3, 900000)
print timeit.Timer("test_3()", setup=setup).repeat(3, 900000)
print timeit.Timer("test_4()", setup=setup).repeat(3, 900000)
print timeit.Timer("test_5()", setup=setup).repeat(3, 900000)
print timeit.Timer("test_6()", setup=setup).repeat(3, 900000)
print timeit.Timer("test_7()", setup=setup).repeat(3, 900000)


> [2.281613943830961, 2.2719342631547077, 2.261691106209631]
> [2.311480238815406, 2.318420542148333, 2.3552384305184493]
> [2.3824197456864304, 2.3457239951596485, 2.3353268829498646]
> [2.312442972404032, 2.318053102249902, 2.3054072168069872]
> [2.3482314132374853, 2.3403386400002475, 2.330108825844775]
> [2.424549090688892, 2.4346475296851438, 2.429691196530058]
> [2.3259756401716487, 2.333549212826732, 2.32049893822186]
Run Code Online (Sandbox Code Playgroud)

我对不同的重复进行了不同的测试。差异并不大,但在所有测试中,zfill解决方案都是最快的。


Laf*_*tar 5

如果您想要填充一个整数,并同时限制有效数字(使用 f 字符串):

a = 4.432
>> 4.432
a = f'{a:04.1f}'
>> '04.4'
Run Code Online (Sandbox Code Playgroud)

f'{a:04.1f}'这将转换为 1 个小数点/(浮点)点,向左填充数字直至总共 4 个字符。