gpt4 book ai didi

python - 在 Python 中是否需要按 '\r\n ' 剥离字符串?

转载 作者:太空宇宙 更新时间:2023-11-04 04:23:21 25 4
gpt4 key购买 nike

在Java中,需要使用\r\n进行剥离,例如split( "\r\n") is not splitting my string in java

但是 \r\n 在 Python 中是必需的吗? 以下是真的吗?

str.strip() == str.strip('\r\n ')

来自docs :

Return a copy of the string with the leading and trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped

从这里CPython test , str.strip() 似乎在剥离:

 \t\n\r\f\v

谁能告诉我 CPython 中执行字符串剥离的代码?

最佳答案

您在寻找这些线路吗?

https://github.com/python/cpython/blob/e42b705188271da108de42b55d9344642170aa2b/Objects/unicodeobject.c#L12222-L12247

#define LEFTSTRIP 0
#define RIGHTSTRIP 1
#define BOTHSTRIP 2

/* Arrays indexed by above */
static const char *stripfuncnames[] = {"lstrip", "rstrip", "strip"};

#define STRIPNAME(i) (stripfuncnames[i])

/* externally visible for str.strip(unicode) */
PyObject *
_PyUnicode_XStrip(PyObject *self, int striptype, PyObject *sepobj)
{
void *data;
int kind;
Py_ssize_t i, j, len;
BLOOM_MASK sepmask;
Py_ssize_t seplen;

if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)
return NULL;

kind = PyUnicode_KIND(self);
data = PyUnicode_DATA(self);
len = PyUnicode_GET_LENGTH(self);
seplen = PyUnicode_GET_LENGTH(sepobj);
sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),
PyUnicode_DATA(sepobj),
seplen);

i = 0;
if (striptype != RIGHTSTRIP) {
while (i < len) {
Py_UCS4 ch = PyUnicode_READ(kind, data, i);
if (!BLOOM(sepmask, ch))
break;
if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
break;
i++;
}
}

j = len;
if (striptype != LEFTSTRIP) {
j--;
while (j >= i) {
Py_UCS4 ch = PyUnicode_READ(kind, data, j);
if (!BLOOM(sepmask, ch))
break;
if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)
break;
j--;
}

j++;
}

return PyUnicode_Substring(self, i, j);
}

关于python - 在 Python 中是否需要按 '\r\n ' 剥离字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54017313/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com