我在用split('\n')
获取一个字符串中的行,发现''.split()
返回的是一个空列表,[]
,而 ''.split('\n')
返回 ['']
。这种差异有什么具体原因吗?
还有没有更方便的方法来计算字符串中的行数?
最佳答案
Question: I am using
split('\n')
to get lines in one string, and found that''.split()
returns an empty list,[]
, while''.split('\n')
returns['']
.
str.split()
方法有两种算法。如果没有给出参数,它会在重复运行的空白处 split 。但是,如果给定参数,则将其视为单个分隔符,不会重复运行。
在拆分空字符串的情况下,第一种模式(无参数)将返回一个空列表,因为空格被吃掉并且没有值可以放入结果列表中。
相比之下,第二种模式(使用 \n
等参数)将生成第一个空字段。考虑一下如果你写了 '\n'.split('\n')
,你会得到两个字段(一个拆分,给你两半)。
Question: Is there any specific reason for such a difference?
当数据在具有可变数量空白的列中对齐时,第一种模式很有用。例如:
>>> data = '''\
Shasta California 14,200
McKinley Alaska 20,300
Fuji Japan 12,400
'''
>>> for line in data.splitlines():
print(line.split())
['Shasta', 'California', '14,200']
['McKinley', 'Alaska', '20,300']
['Fuji', 'Japan', '12,400']
第二种模式适用于分隔数据,例如 CSV其中重复的逗号表示空字段。例如:
>>> data = '''\
Guido,BDFL,,Amsterdam
Barry,FLUFL,,USA
Tim,,,USA
'''
>>> for line in data.splitlines():
print(line.split(','))
['Guido', 'BDFL', '', 'Amsterdam']
['Barry', 'FLUFL', '', 'USA']
['Tim', '', '', 'USA']
注意,结果字段的数量比分隔符的数量大一。想想剪断一根绳子。如果你没有剪裁,你只有一件。切一刀,出两片。进行两次切割,得到三片。 Python 的 str.split(delimiter)
方法也是如此:
>>> ''.split(',') # No cuts
['']
>>> ','.split(',') # One cut
['', '']
>>> ',,'.split(',') # Two cuts
['', '', '']
Question: And is there any more convenient way to count lines in a string?
是的,有几种简单的方法。一用str.count()
和其他用途str.splitlines()
.除非最后一行缺少 \n
,否则两种方式都会给出相同的答案。如果缺少最后的换行符,str.splitlines
方法将给出准确的答案。一种更快且准确的技术使用 count 方法,但随后将其校正为最终换行符:
>>> data = '''\
Line 1
Line 2
Line 3
Line 4'''
>>> data.count('\n') # Inaccurate
3
>>> len(data.splitlines()) # Accurate, but slow
4
>>> data.count('\n') + (not data.endswith('\n')) # Accurate and fast
4
Question from @Kaz: Why the heck are two very different algorithms shoe-horned into a single function?
str.split
的签名大约有 20 年的历史,那个时代的许多 API 都是严格实用的。虽然不完美,但方法签名也不是“可怕的”。在大多数情况下,Guido 的 API 设计选择经受住了时间的考验。
当前的 API 并非没有优势。考虑以下字符串:
ps_aux_header = 'USER PID %CPU %MEM VSZ'
patient_header = 'name,age,height,weight'
当被要求将这些字符串分解为字段时,人们倾向于使用同一个英文单词“split”来描述两者。当被要求阅读诸如 fields = line.split()
或 fields = line.split(',')
之类的代码时,人们倾向于将这些语句正确解释为“splits一行到字段中”。
Microsoft Excel 的 text-to-columns tool做出了类似的 API 选择并 在同一个工具中结合了两种分割算法。尽管涉及多个算法,但人们似乎将场 split 建模为一个单一的概念。
关于python - 在 Python 中拆分空字符串时,为什么 split() 返回一个空列表,而 split ('\n' ) 返回 ['']?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16645083/
相关文章:
linux - ELF文件格式中的section和segment有什么区别
javascript - 可以使用 scrapy 从使用 AJAX 的网站中抓取动态内容吗?
linux - 重新加载 Flash 17 次会导致错误 #2046 并需要重新启动浏览器
linux - 有没有办法检查是否有指向目录的符号链接(symbolic link)?
linux - Git 状态忽略行尾/相同文件/windows & linux 环境/dropbox
python - Python 3.3+ 中的包不需要 __init__.py