如何在Python中实现字符串乘法?

时间:2014-07-11 17:29:09

标签: python string multiplication cpython

Python允许字符串乘以整数:

>>> 'hello' * 5
'hellohellohellohellohello'

如何在CPython中实现?

我特别感谢指向源代码的指针; the Mercurial repository是一个超越我导航能力的迷宫。

2 个答案:

答案 0 :(得分:5)

对于Python 3.x,可以在Objects/unicodeobject.c中找到实现。具体来说,它始于line 12175,其中unicode_repeat已定义:

static PyObject*
unicode_repeat(PyObject *str, Py_ssize_t len)
{
    PyObject *u;
    Py_ssize_t nchars, n;

    if (len < 1)
        _Py_RETURN_UNICODE_EMPTY();

    /* no repeat, return original string */
    if (len == 1)
        return unicode_result_unchanged(str);

    if (PyUnicode_READY(str) == -1)
        return NULL;

    if (PyUnicode_GET_LENGTH(str) > PY_SSIZE_T_MAX / len) {
        PyErr_SetString(PyExc_OverflowError,
                        "repeated string is too long");
        return NULL;
    }
    nchars = len * PyUnicode_GET_LENGTH(str);

    u = PyUnicode_New(nchars, PyUnicode_MAX_CHAR_VALUE(str));
    if (!u)
        return NULL;
    assert(PyUnicode_KIND(u) == PyUnicode_KIND(str));

    if (PyUnicode_GET_LENGTH(str) == 1) {
        const int kind = PyUnicode_KIND(str);
        const Py_UCS4 fill_char = PyUnicode_READ(kind, PyUnicode_DATA(str), 0);
        if (kind == PyUnicode_1BYTE_KIND) {
            void *to = PyUnicode_DATA(u);
            memset(to, (unsigned char)fill_char, len);
        }
        else if (kind == PyUnicode_2BYTE_KIND) {
            Py_UCS2 *ucs2 = PyUnicode_2BYTE_DATA(u);
            for (n = 0; n < len; ++n)
                ucs2[n] = fill_char;
        } else {
            Py_UCS4 *ucs4 = PyUnicode_4BYTE_DATA(u);
            assert(kind == PyUnicode_4BYTE_KIND);
            for (n = 0; n < len; ++n)
                ucs4[n] = fill_char;
        }
    }
    else {
        /* number of characters copied this far */
        Py_ssize_t done = PyUnicode_GET_LENGTH(str);
        const Py_ssize_t char_size = PyUnicode_KIND(str);
        char *to = (char *) PyUnicode_DATA(u);
        Py_MEMCPY(to, PyUnicode_DATA(str),
                  PyUnicode_GET_LENGTH(str) * char_size);
        while (done < nchars) {
            n = (done <= nchars-done) ? done : nchars-done;
            Py_MEMCPY(to + (done * char_size), to, n * char_size);
            done += n;
        }
    }

    assert(_PyUnicode_CheckConsistency(u, 1));
    return u;
}

稍后,在line 13703上,此功能作为PyUnicode对象的sq_repeatPySequenceMethods广告位提供。

答案 1 :(得分:5)

注意:我将回答Python 3,其中字符串类型称为PyUnicode。 Python 2很相似。

当执行BINARY_MULTIPLY操作码时(在Python/ceval.c中),可以调用两个可能的插槽:PyNumberMethods.nb_multiplyPySequenceMethods.sq_repeat。 (这位于PyNumber_Multiply,位于Objects/abstract.c):

PyObject *
PyNumber_Multiply(PyObject *v, PyObject *w)
{
    PyObject *result = binary_op1(v, w, NB_SLOT(nb_multiply));
    if (result == Py_NotImplemented) {
        // call sq_repeat on either side if available

PyUnicodeunicode_repeat中实现后者:

static PyObject*
unicode_repeat(PyObject *str, Py_ssize_t len)
{
    // ...