【问题标题】:Does split("\n") add a new line?split("\n") 是否添加新行?
【发布时间】:2013-08-08 14:11:49
【问题描述】:

文件 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

那是为什么呢?

【问题讨论】:

    标签: python python-2.7 split


    【解决方案1】:

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

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

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

    split()不同,当给定分隔符字符串sep时,此方法为空字符串返回一个空列表,并且终端换行符不会导致额外的行。

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

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

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

    【讨论】:

    • 非常感谢!您的回答也很有用!我从您的回答中学到了一些新东西!
    【解决方案2】:

    你可能有一个尾随换行符:

    >>> s = 'a\nb\nc\n'  # <-- notice the \n at the end
    >>>
    >>> s.split('\n')
    ['a', 'b', 'c', '']
    >>>
    >>> s.splitlines()
    ['a', 'b', 'c']
    

    注意split() 在末尾留下一个空字符串,而splitlines() 没有。

    顺便说一句,你不应该使用 str 作为变量名,因为它已经被 built-in function 占用了。

    【讨论】:

    • 但是文件的内容是'a\nb\nc',没有尾随换行符!
    • @user1936154 打印arr会看到什么?
    • @user1936154 我很确定你有一个尾随换行符。
    • @user1936154:您的输出与您的断言相矛盾。尾随 '' 证明有一个尾随换行符。
    • 我在linux终端看到的是:
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-27
    • 1970-01-01
    • 1970-01-01
    • 2014-04-14
    • 2020-11-02
    相关资源
    最近更新 更多