gpt4 book ai didi

python - 对于没有参数的情况,str.split 是如何实现的

转载 作者:行者123 更新时间:2023-12-05 06:44:21 28 4
gpt4 key购买 nike

当没有给出分隔符时,Python 是否使用正则表达式拆分?

我无法查看 str.__file__other solutions work 也无法查看这里因为 splitstr 类型的函数(虽然它是内置的)。

例如'a\t\t\tb' --> ['a', 'b']

背景对于性能至关重要的许多文件,我正在考虑用单个空格替换所有相邻的空格,尽管我想知道正则表达式拆分是否足够快:也许内置显示了更好的方法。

最佳答案

首先,str 内置于 python 中,这意味着要查看 str.split 的源代码,您将不得不深入研究C source code定义的地方。

现在,进入您的实际问题。我有一种感觉 re.sub 不仅会矫枉过正,而且比使用内置的 str.split 还要慢(完全披露:我没有时间数据来支持这一点- 这只是我的一种感觉)。

现在,str.split 默认在空格处拆分(它有一个可选 参数,可用于指定要拆分的字符)。它还拆分任意数量的连续空白字符。现在,这意味着如果您有一个包含空白字符的字符串,对该字符串调用 str.split 将返回一个非空子字符串列表,其中不包含任何空白字符任何。因此,如果您的字符串具有不同种类的连续空白字符,那么这些空白字符的处理方式没有区别。

举几个例子:

In [31]: s = 'hello world'  # one space

In [32]: s.split()
Out[32]: ['hello', 'world']

In [33]: s = 'hello \tworld' # multiple consecutive whitespace characters

In [34]: s.split()
Out[34]: ['hello', 'world']

In [35]: s = 'hello\tworld' # a different whitespace character

In [36]: s.split()
Out[36]: ['hello', 'world']

In [37]: s = 'hello\t\tworld' # multiple consecutive tab characters

In [38]: s.split()
Out[38]: ['hello', 'world']

In [39]: s = 'hello world' # multiple consecutive space characters

In [40]: s.split()
Out[40]: ['hello', 'world']

如您所见,您的空格如何存在并不重要 - 想想 str.split 当“至少一个空白字符”出现时拆分。

现在,如果您想用一个空格替换所有连续的空白字符,您可以使用 str.splitstr.join 来实现:

In [41]: ' '.join(['hello', 'world'])  # join the strings 'hello' and 'world' with a space between them
Out[41]: 'hello world'

In [42]: s = 'hello world' # notice two spaces between 'hello' and 'world'

In [43]: ' '.join(s.split())
Out[43]: 'hello world' # notice only one space between 'hello' and 'world'

关于python - 对于没有参数的情况,str.split 是如何实现的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29662070/

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