Python - 使用默认split()时删除\ n?

时间:2016-09-22 09:42:07

标签: python

我正在处理字符串,我从命令行获取输入。例如,使用此输入:

format driveName "datahere"

当我去string.split()时,它出现为:

>>> input.split()
['format, 'driveName', '"datahere"']

这就是我想要的。

但是,当我将其指定为string.split(“”,2)时,我得到:

>>> input.split(' ', 2)
['format\n, 'driveName\n', '"datahere"']

有谁知道为什么以及如何解决这个问题?我认为这可能是因为我在Windows上创建它并在Unix上运行,但是当我在unix中使用nano时会出现同样的问题。

第三个参数(数据)可能包含换行符,所以我谨慎不要使用全新的换行符。

3 个答案:

答案 0 :(得分:2)

split()中的默认分隔符是包含换行符\n和空格的所有空格。

以下是docs on split所说的内容:

str.split([sep[, maxsplit]])

If sep is not specified or is None, a different splitting algorithm is 
applied: runs of consecutive whitespace are regarded as a single 
separator, and the result will contain no empty strings at the start 
or end if the string has leading or trailing whitespace. 

定义新的sep时,它只使用该分隔符split字符串。

答案 1 :(得分:1)

默认str.split定位了许多“空白字符”,包括制表符和其他字符。如果您执行str.split(' '),则告诉它仅在' '(空格)上拆分 。您可以通过指定None获取默认行为,如str.split(None, 2)

根据您的实际用例(您的示例不会复制问题......),可能有更好的方法来执行此操作。由于您的示例输出意味着换行符作为分隔符,您应该考虑明确地拆分它们。

inp = """
format
driveName
datahere
datathere
"""
inp.strip().split('\n', 2)
# ['format', 'driveName', 'datahere\ndatathere']

这允许您在第一个和第二个项目中包含空格(和制表符等)。

答案 2 :(得分:0)

使用input.split(None, 2) 获取具有限制的默认空白分割行为:

input()

这会使input.split() end 处的空格保持不变。

或者你可以在之后删除这些值;这将从每个结果字符串的开头和结尾(而不是中间)中删除空格,就像[v.strip() for v in input.split(' ', 2)] 一样:

{{1}}