Python 允许字符串乘以整数:
>>> 'hello' * 5
'hellohellohellohellohello'
这是如何在 CPython 中实现的?
我特别感谢指向源代码的指针; the Mercurial repository是一个超出我导航能力的迷宫。
最佳答案
对于 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 上, 此函数作为 sq_repeat
提供PySequenceMethods
的插槽PyUnicode
对象。
关于python - CPython 中的字符串乘法是如何实现的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24703315/