如何在数字字符串的左边加上零,使字符串具有特定的长度?
当前回答
除了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-string的文档。
其他回答
哪种最适合用零填充数字字符串,即数字字符串具有特定长度?
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'
您也可以重复“0”,将其前置到str(n)并获得最右侧的宽度切片。又快又脏的小表情。
def pad_left(n, width, pad="0"):
return ((pad * width) + str(n))[-width:]
要填充字符串:
>>> 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个字符长度的字符串,根据需要进行填充:
>>> s = 'test'
>>> s.rjust(10, '0')
>>> '000000test'
对于使用f-string的Python 3.6+:
>>> i = 1
>>> f"{i:0>2}" # Works for both numbers and strings.
'01'
>>> f"{i:02}" # Works only for numbers.
'01'
对于Python 2.6到Python 3.5:
>>> "{:0>2}".format("1") # Works for both numbers and strings.
'01'
>>> "{:02}".format(1) # Works only for numbers.
'01'
这些标准格式说明符是[[fill]align][minimumwid]和[0][minimupwid]。
推荐文章
- 如何排序mongodb与pymongo
- 不可变与可变类型
- 列表是线程安全的吗?
- 操作系统。makdirs在我的路径上不理解“~”
- 如何在Django模板中获得我的网站的域名?
- 如何删除表中特定列的第一个字符?
- 在django Forms中定义css类
- 如何在Python中scp ?
- Numpy Max vs amax vs maximum
- 我应该如何从字符串中删除所有的前导空格?- - - - - -斯威夫特
- 我应该在.gitignore文件中添加Django迁移文件吗?
- 每n行有熊猫
- 实例属性attribute_name定义在__init__之外
- 如何获取在Python中捕获的异常的名称?
- 第一次出现的值大于现有值的Numpy