ChatGPT解决这个技术问题 Extra ChatGPT

如何用零填充字符串?

如何在左侧填充零的数字字符串,以使字符串具有特定长度?


M
Mateen Ulhaq

填充字符串:

>>> 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

String formatting documentation


评论 python >= 2.6 不正确。该语法不适用于 python >= 3。您可以将其更改为 python < 3,但我是否可以建议始终使用括号并完全省略注释(鼓励推荐使用)?
请注意,您不需要为格式字符串编号:'{:03d} {:03d}'.format(1, 2) 按顺序隐式分配值。
@JasonR.Coombs:我假设您的意思是 print 语句,什么时候它应该是 Python 3 上的 print 函数?我在括号中进行了编辑;由于只打印了一件事,因此它现在在 Py2 和 Py3 上的工作方式相同。
这些方法中的任何一种都可以适应可变数量的零吗?
你怎么能不使用数字 7 作为你的例子?!? 😲
M
Mateen Ulhaq

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

此示例创建一个 10 个字符长度的字符串,并根据需要进行填充:

>>> s = 'test'
>>> s.rjust(10, '0')
>>> '000000test'

在我看来,应该是't = t.rjust(10, '0'),否则t的值保持不变(至少对我来说)
@StanislavKoncebovski 字符串在 Python 中是不可变的。无论您对它做什么,字符串的值都将始终保持不变,并且如果要更新变量以引用新字符串,则始终必须重新分配。这与 rjust 无关。
以前从没听说过这种方法——擅长隐藏,但现在已经“过时”了!
@Paul D.Eden理论上你可能是对的,但我又检查了一遍,是的,如果你没有像 t = t.rjust(10, '0') 那样赋值,你将不会在 t 中获得'000000test'。我的断言是基于一个测试。我正在使用 Python 3.7。
D
Daniel Morell

除了 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'))

string formattingf-strings 的文档。


@Konrad:“但是,文档说要使用格式。”我知道我参加聚会迟到了,但我想看看你的意思。我看到的文档 (docs.python.org/3/library/stdtypes.html#old-string-formatting) 说使用 format 或其他替代方法“可能有助于避免与 % 插值相关的 [上述] 错误”。这不是非常强大的“弃用”。
@LarsH 值得注意的是,我的答案中的链接最初指向 % 格式。它现在指向 str.format 格式。 我没有更改链接! 而是重写了该链接背后的 Python 文档网站。除此之外,正如我在您引用的评论中所写的那样,documentation used to have stronger wording 和字面意思是 str.format“应该优于 % 格式”。
A
Asclepius

对于使用 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'

对于 Python 2 到 Python 3.5:

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

V
Victor Barrantes
>>> '99'.zfill(5)
'00099'
>>> '99'.rjust(5,'0')
'00099'

如果你想要相反的:

>>> '99'.ljust(5,'0')
'99000'

j
johnsyweb

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'

R
Russia Must Remove Putin

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

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 函数也由 ljustrjustcenter 调用)。这基本上将内容复制到一个新字符串中并填充填充。

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'

对于性能,是否存在 f 字符串更好的情况,包括 python2 与 python3 的用例?另外,我认为由于 zfill 并不常见,因此链接到文档将有助于您的答案
@eladsilver 取决于您的意图,请记住 +- 的行为,我添加了指向文档的链接!
e
elad silver

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

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


r
ruohola

使用 Python >= 3.6 时,最简洁的方法是将 f-stringsstring formatting 一起使用:

>>> s = f"{1:08}"  # inline with int
>>> s
'00000001'
>>> s = f"{'1':0>8}"  # inline with str
>>> s
'00000001'
>>> n = 1
>>> s = f"{n:08}"  # int variable
>>> s
'00000001'
>>> c = "1"
>>> s = f"{c:0>8}"  # str variable
>>> s
'00000001'

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

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

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

>>> f"{'-1':0>8}"
'000000-1'

u
user1315621

对于数字:

i = 12
print(f"{i:05d}")

输出

00012

我宁愿希望你能得到'00002'。 i>10 的示例也可能是一个好主意。尽管如此,这对我有帮助。
P
Peter Rowell
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 月起就一直在使用这种符号。某事...老狗..某事某事...新花样。


自 1980 年以来......你是一个 60 岁的程序员......你能否就 python 如何解释 "%0*d" % (width, x) 提供更多解释?
N
NBStephens

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

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


它包含在这个答案中:stackoverflow.com/a/57360675/860196
A
Asclepius

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

>>> a = 6340
>>> b = 90210
>>> print '%05d' % a
06340
>>> print '%05d' % b
90210

你是对的,无论如何我更喜欢你对 zfill 的建议
S
Simon Steinberger

快速时序比较:

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]

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


z
zzfima

它也可以:

 h = 2
 m = 7
 s = 3
 print("%02d:%02d:%02d" % (h, m, s))

所以输出将是:“02:07:03”


k
kmario23

另一种方法是使用带有条件检查长度的列表推导。下面是一个演示:

# input list of strings that we want to prepend zeros
In [71]: list_of_str = ["101010", "10101010", "11110", "0000"]

# prepend zeros to make each string to length 8, if length of string is less than 8
In [83]: ["0"*(8-len(s)) + s if len(s) < desired_len else s for s in list_of_str]
Out[83]: ['00101010', '10101010', '00011110', '00000000']

J
Julien Faujanet

我做了一个功能:

def PadNumber(number, n_pad, add_prefix=None):
    number_str = str(number)
    paded_number = number_str.zfill(n_pad)
    if add_prefix:
        paded_number = add_prefix+paded_number
    print(paded_number)

PadNumber(99, 4)
PadNumber(1011, 8, "b'")
PadNumber('7BEF', 6, "#")

输出 :

0099
b'00001011
#007BEF

L
Lafftar

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

a = 4.432
>> 4.432
a = f'{a:04.1f}'
>> '04.4'

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


D
Danra

您也可以重复“0”,将其添加到 str(n) 并获得最右边的宽度切片。快速而肮脏的小表情。

def pad_left(n, width, pad="0"):
    return ((pad * width) + str(n))[-width:]

不过,这只适用于正数。如果你也想要底片,它会变得有点复杂。但是,如果您不介意这种事情,这种表达方式适用于快速而肮脏的工作。
我完全不知道为什么这被否决了。如果是因为它在负数上不够公平,那么将填充为零的压倒性原因是id号。如果您的身份证号码为负数,我认为您有更大的问题......您是否希望您的垫子采用“00000-1234”的形式?还是'-000001234'?老实说,这个答案有效的问题,它很简单,很干净,它是可扩展的。它可能不是 zfill,但如果它回答了这个问题,它应该被赞成。