字串:
>>> 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
字符串格式化文档 。
只需使用字符串对象的rjust方法即可。
本示例将使一个 10 个字符长的字符串,必要时进行填充。
>>> t = 'test'
>>> t.rjust(10, '0')
>>> '000000test'
除了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'))
字符串格式和f-strings 的文档。
这适用于 Python 2 和 Python 3:
>>> "{:0>2}".format("1") # Works for both numbers and strings.
'01'
>>> "{:02}".format(1) # Works only for numbers.
'01'
与使用 f 字符串的 Python 3.6 + 配合使用:
>>> i = 1
>>> f"{i:0>2}" # Works for both numbers and strings.
'01'
>>> f"{i:02}" # Works only for numbers.
'01'
>>> '99'.zfill(5)
'00099'
>>> '99'.rjust(5,'0')
'00099'
如果您想要相反的话:
>>> '99'.ljust(5,'0')
'99000'
str(n).zfill(width)
将与string
s, int
, float
s 一起使用,并且与 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'
对于那些来这里了解的人,而不仅仅是一个快速的答案。我特别针对时间字符串执行以下操作:
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####'
“0” 符号用 “2” 填充字符替换,默认为空白
“>” 符号会分配字符串左侧所有 2 个 “0” 字符
“:” 符号 format_spec
将数字字符串填充到左侧的零的最有效方法是什么(即数字字符串具有特定的长度)?
str.zfill
专门用于执行此操作:
>>> '1'.zfill(4)
'0001'
请注意,它专门用于按要求处理数字字符串,并将+
或-
移至字符串的开头:
>>> '+1'.zfill(4)
'+001'
>>> '-1'.zfill(4)
'-001'
这是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.
这也是替代方法最有效的方法:
>>> 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
为了最好地将苹果与苹果进行%
方法比较(请注意,它实际上速度较慢),否则将预先计算:
>>> min(timeit.repeat(lambda: '1'.zfill(0 or 4)))
0.19728074967861176
>>> min(timeit.repeat(lambda: '%04d' % (0 or 1)))
0.2347015216946602
稍加挖掘,我在Objects/stringlib/transmogrify.h
找到了zfill
方法的实现:
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;
}
让我们来看一下这个 C 代码。
它首先在位置上解析参数,这意味着它不允许关键字参数:
>>> '1'.zfill(width=4)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: zfill() takes no keyword arguments
然后,它检查长度是否相同或更长,在这种情况下,它将返回字符串。
>>> '1'.zfill(0)
'1'
zfill
调用pad
(此pad
函数也被ljust
, rjust
和center
调用)。这基本上将内容复制到一个新的字符串中并填充填充。
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;
}
调用pad
, zfill
将所有原来在+
或-
之前的字符串移动到字符串的开头。
请注意,原始字符串实际上不需要是数字:
>>> '+foo'.zfill(10)
'+000000foo'
>>> '-foo'.zfill(10)
'-000000foo'
width = 10
x = 5
print "%0*d" % (width, x)
> 0000000005
有关所有激动人心的细节,请参见打印文档!
适用于 Python 3.x 的更新(7.5 年后)
最后一行现在应该是:
print("%0*d" % (width, x))
即print()
现在是一个函数,而不是一个语句。请注意,我仍然更喜欢 Old School printf()
样式,因为 IMNSHO 读起来更好,并且因为,自从 1980 年 1 月以来,我一直在使用该表示法。新花样。
当使用 Python >= 3.6
,最干净的方法是使用字符串格式的 f 字符串 :
>>> s = f"{1:08}" # inline with int
>>> s
'00000001'
>>> s = f"{'1':0>8}" # inline with str (works also for ints)
>>> s
'00000001'
>>> n = 1
>>> s = f"{n:08}" # int variable
>>> s
'00000001'
>>> c = "1"
>>> s = f"{c:0>8}" # str variable (works also for ints)
>>> s
'00000001'