gpt4 book ai didi

python - split ("\n") 是否添加新行?

转载 作者:行者123 更新时间:2023-12-05 08:59:08 25 4
gpt4 key购买 nike

文件abc的内容:

a
b
c

代码是

data_fh = open("abc")
str = data_fh.read()
arr = str.split("\n")
print len(arr)
data_fh.seek(0)
arr = data_fh.read().splitlines()
print len(arr)

但是输出是:

4
3

那是为什么呢?

最佳答案

因为 .splitlines() 不包括末尾的空行,而 .split('\n') 为最后一个 返回一个空字符串>...\n:

>>> 'last\n'.split('\n')
['last', '']
>>> 'last\n'.splitlines()
['last']

str.splitlines() documentation 中明确提到了这一点:

Unlike split() when a delimiter string sep is given, this method returns an empty list for the empty string, and a terminal line break does not result in an extra line.

如果没有尾随换行符,输出是相同的:

>>> 'last'.split('\n')
['last']
>>> 'last'.splitlines()
['last']

换句话说,str.split() 不会添加任何内容,但str.splitlines() 会删除。

关于python - split ("\n") 是否添加新行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18128291/

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