Hướng dẫn python format string padding zero - chuỗi định dạng python không đệm

Cách pythonic nhất để đệm một chuỗi số với số 0 ở bên trái, tức là, vì vậy chuỗi số có độ dài cụ thể?

>>> 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.
9 đặc biệt nhằm mục đích làm điều này:

>>> '1'.zfill(4)
'0001'

Lưu ý rằng nó được dự định cụ thể để xử lý các chuỗi số theo yêu cầu và di chuyển một

>>> 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
0 hoặc
>>> 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
1 sang đầu chuỗi:

>>> '+1'.zfill(4)
'+001'
>>> '-1'.zfill(4)
'-001'

Đây là sự giúp đỡ trên

>>> 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.
9:

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

Màn biểu diễn

Đây cũng là hiệu suất nhất của các phương pháp thay thế:

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

Để so sánh tốt nhất táo với táo cho phương pháp

>>> 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
3 (lưu ý nó thực sự chậm hơn), nếu không sẽ tính trước:

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

Thực hiện

Với một chút đào, tôi đã tìm thấy việc triển khai phương thức

>>> 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
4 trong
>>> 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
5:

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

Hãy đi qua mã C này.

Trước tiên, nó phân tích đối số ở vị trí, có nghĩa là nó không cho phép các đối số từ khóa:

>>> '1'.zfill(width=4)
Traceback (most recent call last):
  File "", line 1, in 
TypeError: zfill() takes no keyword arguments

Sau đó, nó kiểm tra xem nó có cùng độ dài hoặc dài hơn không, trong trường hợp đó nó trả về chuỗi.

>>> '1'.zfill(0)
'1'

>>> 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
4 gọi
>>> 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
7 (hàm
>>> 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
7 này cũng được gọi bởi
>>> 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
9,
>>> min(timeit.repeat(lambda: '1'.zfill(0 or 4)))
0.19728074967861176
>>> min(timeit.repeat(lambda: '%04d' % (0 or 1)))
0.2347015216946602
0 và
>>> min(timeit.repeat(lambda: '1'.zfill(0 or 4)))
0.19728074967861176
>>> min(timeit.repeat(lambda: '%04d' % (0 or 1)))
0.2347015216946602
1 cũng như vậy). Điều này về cơ bản sao chép nội dung vào một chuỗi mới và điền vào phần đệm.

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

Sau khi gọi

>>> 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
7,
>>> 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
4 di chuyển bất kỳ trước đó trước
>>> 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
0 hoặc
>>> 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
1 đến đầu chuỗi.

Lưu ý rằng để chuỗi ban đầu thực sự là không cần số:

>>> '+foo'.zfill(10)
'+000000foo'
>>> '-foo'.zfill(10)
'-000000foo'

Bạn đã bao giờ có một chuỗi và muốn biến nó thành một độ dài nhất định bằng cách thêm số không vào nó? Bạn có thể gõ nó ra. Nhưng chúng tôi là lập trình viên, chúng tôi ghét gõ! Chắc chắn phải có một cách để viết mã này? & NBSP;

Hướng dẫn python format string padding zero - chuỗi định dạng python không đệm

Để pad zeros vào một chuỗi, hãy sử dụng phương thức

>>> min(timeit.repeat(lambda: '1'.zfill(0 or 4)))
0.19728074967861176
>>> min(timeit.repeat(lambda: '%04d' % (0 or 1)))
0.2347015216946602
6. Phải mất một đối số: Độ dài cuối cùng của chuỗi bạn muốn và đệm chuỗi với số không ở bên trái.

>>> '+1'.zfill(4)
'+001'
>>> '-1'.zfill(4)
'-001'
0

Nếu bạn nhập giá trị nhỏ hơn độ dài của chuỗi, nó sẽ trả về chuỗi không được sửa đổi.

>>> '+1'.zfill(4)
'+001'
>>> '-1'.zfill(4)
'-001'
1

Hãy cùng đi sâu vào một tổng quan chi tiết hơn về đệm chuỗi và các tùy chọn khác nhau mà bạn có.string padding and the different options you have.

Video

Chúng tôi khuyên bạn nên xem video cho bài viết này. Các ý tưởng có thể khó hiểu lúc đầu. Có Adam để hướng dẫn bạn làm cho nó dễ dàng hơn nhiều.

Python làm thế nào để chuyển số zeros vào một video chuỗi

Phương pháp đệm chuỗi python

Python có một số phương thức chuỗi tích hợp cho chuỗi pad. Bạn không giới hạn ở số không nhưng có thể đệm với bất kỳ ký tự nào. & NBSP;

Tên của họ rất dễ nhớ:

  • >>> 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
    
    9 - Chuỗi trả về trái chính đáng & nbsp;
  • >>> min(timeit.repeat(lambda: '1'.zfill(0 or 4)))
    0.19728074967861176
    >>> min(timeit.repeat(lambda: '%04d' % (0 or 1)))
    0.2347015216946602
    
    0 - Chuỗi trả về đúng
  • >>> min(timeit.repeat(lambda: '1'.zfill(0 or 4)))
    0.19728074967861176
    >>> min(timeit.repeat(lambda: '%04d' % (0 or 1)))
    0.2347015216946602
    
    1 - Chuỗi trả về trung tâm

Tất cả đều có cùng một cú pháp

>>> '+1'.zfill(4)
'+001'
>>> '-1'.zfill(4)
'-001'
2
  • Đối số đầu tiên là
    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;
    }
    
    0. Đó là độ dài của chuỗi bạn muốn quay lại. Nếu bạn nhập chiều rộng nhỏ hơn
    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;
    }
    
    1, Python sẽ trả về
    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;
    }
    
    2 không được sửa đổi. & NBSP;length of the string you want to return. If you enter a width smaller than
    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;
    }
    
    1, Python returns
    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;
    }
    
    2 unmodified. 
  • Đối số thứ hai,
    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;
    }
    
    3, là tùy chọn. Sử dụng là để chỉ định ký tự bạn muốn sử dụng để đệm chuỗi của bạn. Theo mặc định, nó là một không gian nhưng bạn có thể sử dụng bất cứ thứ gì. Nếu bạn vượt qua một chuỗi dài hơn một ký tự, Python sẽ tăng
    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;
    }
    
    4.character you want to use to pad your string. By default, it is a space but you can use anything. If you pass a string longer than one character, Python raises a
    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;
    }
    
    4.

Bạn có muốn phát triển các kỹ năng của một Python Professional toàn diện trong khi được trả tiền trong quá trình này không? Trở thành một freelancer Python và đặt hàng cuốn sách của bạn rời khỏi cuộc đua chuột với Python trên Amazon (Kindle/Print)!well-rounded Python professional—while getting paid in the process? Become a Python freelancer and order your book Leaving the Rat Race with Python on Amazon (Kindle/Print)!

Hướng dẫn python format string padding zero - chuỗi định dạng python không đệm

Hãy cùng xem xét một số ví dụ cho mỗi phương pháp.

Ví dụ str.ljust ()

>>> '+1'.zfill(4)
'+001'
>>> '-1'.zfill(4)
'-001'
3

Ví dụ str.rjust ()

>>> '+1'.zfill(4)
'+001'
>>> '-1'.zfill(4)
'-001'
4

Ví dụ Str.Center

Lưu ý: Nếu giữa chuỗi của bạn không chính xác là giữa chiều rộng, Python sẽ hơi còn lại biện minh cho nó. Đây là trường hợp trong tất cả các ví dụ dưới đây sử dụng chiều rộng chẵn.

>>> '+1'.zfill(4)
'+001'
>>> '-1'.zfill(4)
'-001'
5

Phương pháp định dạng đệm chuỗi python

Nếu bạn đang sử dụng các câu lệnh

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;
}
5 phức tạp, bạn sẽ muốn sử dụng F-Strings hoặc phương thức định dạng tại một số điểm. Rất may, chúng ta cũng có thể dễ dàng đệm dây theo cách này.

L-Strings được giới thiệu trong Python 3.6. Chúng là tiêu chuẩn de-facto cho định dạng chuỗi trong Python. Nhưng chúng tôi sẽ bao gồm phương pháp

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;
}
6 để hoàn thiện. & NBSP;

Kiểm tra các tài liệu Python chính thức để biết tổng quan chi tiết. Cảnh báo, họ rất khó hiểu. Vì vậy, don lồng được đưa ra nếu bạn mất một lúc để hiểu chúng.

Python String Padding sử dụng F-String

F-Strings là vô cùng mạnh mẽ. Chúng tôi sẽ chỉ đề cập đến cách pad String nhưng hãy xem bài viết này để biết tổng quan chi tiết. & NBSP;how to pad strings but check out this article for a detailed overview. 

Bạn biểu thị các chuỗi F bằng cách đặt một

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;
}
7 hoặc
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;
}
8 trước một chuỗi. Tính năng chính của họ được gọi là trường thay thế. Nó được biểu thị bằng niềng răng xoăn
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;
}
9. Bên trong niềng răng, bạn có thể đặt các biến, biểu thức hoặc thậm chí các hàm. Điều này cực kỳ hữu ích vì nó mang lại cho chuỗi của bạn rất nhiều sự linh hoạt. & NBSP;replacement field. It is denoted by curly braces
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;
}
9. Inside the braces, you can put variables, expressions or even functions. This is incredibly helpful as it gives your strings lots of flexibility. 

Đối với bài viết này, chúng tôi sẽ tập trung vào việc gọi các biến trong các chuỗi, ví dụ:

>>> '+1'.zfill(4)
'+001'
>>> '-1'.zfill(4)
'-001'
6

Bạn có thể sửa đổi chuỗi bên trong trường thay thế. Bạn có thể đệm, căn chỉnh và thay đổi chiều dài của nó. Đây được gọi là đặc tả định dạng trong Python hoặc format_spec viết tắt. Trong một chuỗi F, bạn chỉ định điều này bằng cách sử dụng ruột

>>> '1'.zfill(width=4)
Traceback (most recent call last):
  File "", line 1, in 
TypeError: zfill() takes no keyword arguments
0. Tất cả mọi thứ sau đại tràng là một lựa chọn định dạng. Nó sẽ không được in lên màn hình. Hãy cùng nhìn vào cú pháp để pad, căn chỉnh và thay đổi độ dài của một chuỗi.format specification in Python, or format_spec for short. In an f-string, you specify this using a colon
>>> '1'.zfill(width=4)
Traceback (most recent call last):
  File "", line 1, in 
TypeError: zfill() takes no keyword arguments
0. Everything after the colon is a formatting option. It will not be printed to the screen. Let’s look at the syntax to pad, align and change the length of a string.

Chúng tôi gõ những điều sau theo thứ tự này, sau đại tràng

>>> '1'.zfill(width=4)
Traceback (most recent call last):
  File "", line 1, in 
TypeError: zfill() takes no keyword arguments
0

  • điền: ký tự để sử dụng để đệm & nbsp; character to use for padding 
  • Căn chỉnh: Sử dụng hoặc ^ để căn chỉnh bên trái, phải hoặc trung tâm use <, > or ^ to have left, right or center alignment
  • Chiều rộng: Giá trị số nguyên ghi rõ tổng chiều dài của chuỗi integer value stating total length of string

Ví dụ: Vì vậy, nếu chúng ta muốn đệm chuỗi của mình bằng số không, tức là điền 0, căn chỉnh phải và có chiều rộng 10, chúng ta sẽ sử dụng: So if we want to pad our string with zeros, i.e. fill 0, right align and have width 10, we would use

  • điền:
    >>> '1'.zfill(width=4)
    Traceback (most recent call last):
      File "", line 1, in 
    TypeError: zfill() takes no keyword arguments
    
    2
    >>> '1'.zfill(width=4)
    Traceback (most recent call last):
      File "", line 1, in 
    TypeError: zfill() takes no keyword arguments
    
    2
  • Đúng đúng:
    >>> '1'.zfill(width=4)
    Traceback (most recent call last):
      File "", line 1, in 
    TypeError: zfill() takes no keyword arguments
    
    3
    :
    >>> '1'.zfill(width=4)
    Traceback (most recent call last):
      File "", line 1, in 
    TypeError: zfill() takes no keyword arguments
    
    3
  • Chiều rộng:
    >>> '1'.zfill(width=4)
    Traceback (most recent call last):
      File "", line 1, in 
    TypeError: zfill() takes no keyword arguments
    
    4
    >>> '1'.zfill(width=4)
    Traceback (most recent call last):
      File "", line 1, in 
    TypeError: zfill() takes no keyword arguments
    
    4

Mã này hiển thị ví dụ chính xác này trong hành động:

>>> '+1'.zfill(4)
'+001'
>>> '-1'.zfill(4)
'-001'
7

Hãy để xem những gì xảy ra khi chúng ta thay đổi từng tùy chọn này. Đầu tiên, chúng tôi sẽ chọn một ký tự điền khác.fill character.

>>> '+1'.zfill(4)
'+001'
>>> '-1'.zfill(4)
'-001'
8

Bây giờ chúng tôi sẽ thay đổi sự liên kết. Các dấu hiệu chỉ ra theo hướng căn chỉnh, tức là

>>> '1'.zfill(width=4)
Traceback (most recent call last):
  File "", line 1, in 
TypeError: zfill() takes no keyword arguments
5 được căn chỉnh và lên trên
>>> '1'.zfill(width=4)
Traceback (most recent call last):
  File "", line 1, in 
TypeError: zfill() takes no keyword arguments
6 là căn chỉnh trung tâm.alignment. The sign points in the direction of alignment i.e.
>>> '1'.zfill(width=4)
Traceback (most recent call last):
  File "", line 1, in 
TypeError: zfill() takes no keyword arguments
5 is left align and upwards
>>> '1'.zfill(width=4)
Traceback (most recent call last):
  File "", line 1, in 
TypeError: zfill() takes no keyword arguments
6 is center align.

>>> '+1'.zfill(4)
'+001'
>>> '-1'.zfill(4)
'-001'
9

Cuối cùng, chúng tôi sẽ thay đổi độ dài chuỗi.length.

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

Để đệm nhiều chuỗi, sử dụng nhiều trường thay thế (niềng răng xoăn

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;
}
9).

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

Đệm sử dụng .format ()

Đệm với

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;
}
6 tương tự như F-Strings. & NBSP;

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

Bạn có thể chuyển chuỗi trực tiếp đến

>>> '1'.zfill(width=4)
Traceback (most recent call last):
  File "", line 1, in 
TypeError: zfill() takes no keyword arguments
9 nếu bạn thích:

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

Cú pháp định dạng_spec (mọi thứ sau đại tràng) đều giống nhau khi sử dụng f-string hoặc định dạng. Sự khác biệt là bạn vượt qua

>>> '1'.zfill(0)
'1'
0 đến
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;
}
6 thay vì đặt nó trong trường thay thế
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;
}
9. Hoặc bạn có thể nhập chuỗi trực tiếp vào ________ 56. & nbsp;

Đệm nhiều chuỗi có thể trở nên phức tạp hơn khi sử dụng

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;
}
6. Hãy nói rằng bạn có hai trường thay thế và chuyển hai biến cho
>>> '1'.zfill(0)
'1'
5. Sau đó
>>> '1'.zfill(0)
'1'
0 sẽ đi đến lần đầu tiên và
>>> '1'.zfill(0)
'1'
7 đến lần thứ hai. & Nbsp;

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

Để rõ ràng hơn, bạn có thể tham khảo các đối số của định dạng với các chỉ mục bắt đầu từ 0. Điều này cho phép bạn gọi các biến theo bất kỳ thứ tự nào bạn muốn.

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

Cuối cùng, bạn không cần chỉ định các biến khi bạn sử dụng

>>> '1'.zfill(width=4)
Traceback (most recent call last):
  File "", line 1, in 
TypeError: zfill() takes no keyword arguments
9. Bạn có thể chuyển các chuỗi để thay thế trực tiếp.

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

Bạn nên chọn cái nào-Định dạng hoặc F-String?

Python đã giới thiệu các chuỗi F trong PEP 498. Một trong những lý do cho điều này là do cú pháp

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;
}
6 có thể là dòng chảy, chậm và khó đọc. F-Strings giải quyết tất cả những vấn đề này. Chúng đơn giản, rất nhanh và dễ đọc. Vì vậy, bạn phải luôn luôn sử dụng chúng thay vì
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;
}
6. Tuy nhiên, rất hữu ích khi biết cú pháp
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;
}
6 trong trường hợp bạn đọc nó trong mã người khác. & NBSP;

Python int để chuỗi với số không hàng đầu

Để chuyển đổi số nguyên

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;
}
2 thành một chuỗi với số 0 hàng đầu để nó bao gồm các ký tự
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;
}
3, hãy sử dụng chuỗi định dạng
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;
}
4. Cờ
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;
}
5 trong biểu thức này xác định rằng kết quả là một giá trị thập phân.
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;
}
6 hoàn thành quá trình chuyển đổi chuỗi giống nhau của một số nguyên với các số không hàng đầu.

Thử thách: Cho một số nguyên. Cách chuyển đổi nó thành một chuỗi bằng cách thêm các số không dẫn đầu để chuỗi có một số vị trí cố định.: Given an integer number. How to convert it to a string by adding leading zeros so that the string has a fixed number of positions.

Ví dụ: Đối với Integer 42, bạn muốn điền nó với số không dẫn đầu vào chuỗi sau với 5 ký tự:

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;
}
7.: For integer 42, you want to fill it up with leading zeros to the following string with 5 characters:
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;
}
7.

Trong tất cả các phương pháp, chúng tôi giả định rằng số nguyên có ít hơn 5 ký tự.

Phương pháp 1: Chuỗi định dạng

Phương thức đầu tiên sử dụng tính năng chuỗi định dạng trong Python 3+. Họ cũng được gọi là các lĩnh vực thay thế.

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

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;
}
4 đặt số nguyên i vào chuỗi mới được tạo. Tuy nhiên, nó cho biết ngôn ngữ định dạng sẽ điền vào chuỗi vào
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;
}
3 ký tự với các ____990 hàng đầu bằng hệ thống thập phân. Đây là cách pythonic nhất để thực hiện thử thách này.

Phương pháp 2: Zfill ()

Một cách khác có thể đọc được và pythonic để điền vào chuỗi với 0S hàng đầu là phương thức

>>> '+foo'.zfill(10)
'+000000foo'
>>> '-foo'.zfill(10)
'-000000foo'
1.

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

Phương thức lấy một đối số và đó là số lượng vị trí của chuỗi kết quả. Mỗi mặc định, nó lấp đầy với 0s.

Bài viết liên quan: Python int to String với các số không hàng đầu Python Int to String with Leading Zeros

Bản tóm tắt

Trong bài viết này, bạn đã học được nhiều cách khác nhau mà bạn có thể đệm Zeros (và bất kỳ nhân vật nào khác) cho các chuỗi.

Nếu bạn chỉ muốn pad zeros ở bên trái của chuỗi, không có gì tốt hơn phương pháp

>>> '+foo'.zfill(10)
'+000000foo'
>>> '-foo'.zfill(10)
'-000000foo'
2. Nó được thiết kế để giải quyết vấn đề này.

Để pad các ký tự khác nhau, hãy sử dụng

>>> '+foo'.zfill(10)
'+000000foo'
>>> '-foo'.zfill(10)
'-000000foo'
3,
>>> '+foo'.zfill(10)
'+000000foo'
>>> '-foo'.zfill(10)
'-000000foo'
4 và
>>> '+foo'.zfill(10)
'+000000foo'
>>> '-foo'.zfill(10)
'-000000foo'
5. Hoặc bạn có thể sử dụng F-Strings hoặc phương thức
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;
}
6. & NBSP;

Các phương pháp tích hợp dễ dàng hơn nhiều để học, đọc và thực hiện. Nhưng điều quan trọng là bạn biết tất cả. Bạn sẽ thấy mọi thứ trong tự nhiên!

Đi đâu từ đây

Bạn có muốn kiếm thêm tiền không? Bạn đang làm một công việc 9-5 ngõ cụt? Bạn có mơ ước phá vỡ miễn phí và mã hóa toàn thời gian nhưng không chắc chắn làm thế nào để bắt đầu không? & NBSP;

Trở thành một lập trình viên toàn thời gian là đáng sợ. Có rất nhiều thông tin mã hóa ngoài đó đến nỗi nó áp đảo. & NBSP;

Hầu hết các hướng dẫn đều dạy cho bạn Python và bảo bạn có được một công việc toàn thời gian. & NBSP;

Điều đó ok nhưng tại sao bạn lại muốn một công việc văn phòng khác?

Bạn có khao khát tự do? Bạn có muốn đi du lịch khắp thế giới không? Bạn có muốn dành nhiều thời gian hơn với bạn bè và gia đình của mình không?

Hầu như không có bất kỳ hướng dẫn nào dạy bạn Python và làm thế nào để trở thành ông chủ của chính bạn. Và không có ai dạy bạn cách thực hiện sáu con số mỗi năm.

Cho đến bây giờ. & Nbsp;

Tôi là một freelancer Python toàn thời gian. Tôi làm việc 4 giờ một ngày từ bất cứ nơi nào trên thế giới. Tôi đặt lịch trình của riêng tôi và tỷ lệ hàng giờ. Lịch của tôi được đặt trước vài tháng và tôi có một luồng khách hàng mới liên tục. & NBSP;

Nghe có vẻ quá tốt để trở thành sự thật, phải không?

Không có gì. Tôi muốn cho bạn thấy các bước chính xác tôi đã sử dụng để đến đây. Tôi muốn cho bạn một cuộc sống tự do. Tôi muốn bạn trở thành một lập trình viên sáu con số.

Nhấp vào liên kết bên dưới để xem hội thảo trên web có giá trị thuần túy của tôi. Tôi sẽ chỉ cho bạn các bước chính xác để đưa bạn từ nơi bạn đến với một freelancer Python toàn thời gian. Đây là những phương pháp đã được chứng minh, không BS giúp bạn kết quả nhanh chóng.

Không có vấn đề gì nếu bạn là một người mới làm quen hay Python Pro. Nếu bạn không thực hiện sáu con số/năm với Python ngay bây giờ, bạn sẽ học được điều gì đó từ hội thảo trên web này.

Hội thảo trên web này đã giành chiến thắng trực tuyến mãi mãi. Nhấp vào liên kết bên dưới trước khi các chỗ ngồi lấp đầy và tìm hiểu làm thế nào để trở thành một freelancer Python.

https://blog.finxter.com/webinar-freelancer/

Người giới thiệu

Các tài liệu Python chính thức cho định dạng chuỗi rất khó hiểu. Rất may, có rất nhiều tài nguyên tuyệt vời trực tuyến. Kiểm tra mục yêu thích của chúng tôi dưới đây.

  1. https://www.python.org/dev/peps/pep-0498/ 
  2. https://realpython.com/python-f-strings/
  3. https://docs.python.org/3.8/library/string.html#formatexamples 
  4. https://stackoverflow.com/questions/339007/how-to-pad-zeroes-to-a-string
  5. https://www.tutorialspoint.com/python/string_zfill.htm
  6. http://zetcode.com/python/fstring/
  7. https://pyformat.info/
  8. https://www.tutorialspoint.com/python/string_rjust.htm

Hướng dẫn python format string padding zero - chuỗi định dạng python không đệm

Chuyên gia nhà văn & người tạo nội dung - Khoa học dữ liệu & học máy. Tôi đã giúp các công ty giáo dục tạo ra blog và nội dung video hấp dẫn khoa học dữ liệu cho người mới bắt đầu. Không giống như các đối thủ cạnh tranh của tôi, tôi học các khái niệm mới mỗi ngày và vì vậy hãy hiểu những gì nó giống như là một sinh viên. Các bài viết của tôi là dễ hiểu, hiệu quả và thú vị để đọc. Video của tôi là lạc quan, hấp dẫn và chi tiết. “Để làm việc với tôi, xin vui lòng liên hệ với Upwork https://tinyurl.com/hire-adam-murphy
—–
I help education companies create engaging blog and video content teaching Data Science to beginners. Unlike my competitors, I learn new concepts every day and so understand what it’s like to be a student.
My articles are easy-to-understand, effective and enjoyable to read. My videos are upbeat, engaging and detailed.
—–
To work with me, please reach out on Upwork
https://tinyurl.com/hire-adam-murphy

Làm thế nào để bạn không có một miếng đệm trong Python?

Phương thức chuỗi python zfill () Phương thức Zfill () thêm các số không (0) ở đầu chuỗi, cho đến khi nó đạt đến độ dài được chỉ định. Nếu giá trị của tham số LEN nhỏ hơn chiều dài của chuỗi, không thực hiện được.The zfill() method adds zeros (0) at the beginning of the string, until it reaches the specified length. If the value of the len parameter is less than the length of the string, no filling is done.

Làm thế nào để bạn thực hiện đệm chuỗi trong Python?

Sử dụng phương pháp này, chuỗi được căn chỉnh ở phía bên trái bằng cách chèn đệm vào đầu bên phải của chuỗi ...
Cú pháp: String.ljust (Width, Char) Tham số: ....
Cú pháp: String.Rjust (Width, Char) ....
Cú pháp: String.Center (chiều rộng) ....
Cú pháp: String.zfill (chiều dài) ....
Cú pháp: String.Format (value_1, value_2, value_3, value_4, value_n).

Làm thế nào để bạn tạo một chuỗi số không?

Để pad zeros vào một chuỗi, sử dụng str.Phương thức Zfill ().Nó lấy một đối số: Độ dài cuối cùng của chuỗi bạn muốn và đệm chuỗi với số không ở bên trái ...
LJUST - Chuỗi trả về còn lại hợp lý ..
RJUST - Chuỗi trả về chính đáng ..
Trung tâm - Chuỗi trả về trung tâm ..

Làm thế nào để bạn thêm một số 0 hàng đầu vào một chuỗi trong Python?

Để đệm một chuỗi với các số không dẫn đầu, chúng tôi sử dụng phương thức zfill (), thêm 0 tại điểm bắt đầu của chuỗi để mở rộng kích thước của chuỗi đến kích thước ưa thích.Nói tóm lại, chúng tôi sử dụng phương pháp đệm bên trái, lấy kích thước chuỗi làm đối số và hiển thị chuỗi với đầu ra đệm.use the zfill() method, which adds 0's at the starting point of the string to extend the size of the string to the preferred size. In short, we use the left padding method, which takes the string size as an argument and displays the string with the padded output.