这个语句 (line, str) = str.split("\n", 1) 是什么意思?
what does this statement (line, str) = str.split("\n", 1) mean?
我熟悉 split
函数,我会这样使用它:
str = "Line1-abcdef \nLine2-abc \nLine4-abcd"
print str.split( )
上面会return这个:
['Line1-abcdef', 'Line2-abc', 'Line4-abcd']
简单易行。但是,我遇到了一段包含以下语句的代码:
(line, str) = str.split("\n", 1)
这里有两点我不明白:
split
的第二个参数及其作用。我查看了 here,它显示了生成的行数。这是什么意思?
split
returns 是一个可迭代的向量。为什么要分配给 (line, str)
?这里的(line, str)
是什么意思?
第二个参数maxsplit=1
表示遇到分隔符\n
一次后停止拆分。
因此你只有两部分,你的行和字符串的其余部分。
例如:
str = 'This is one line\nThis is a second line\nThis is a third line'
(line, str) = str.split('\n', 1)
print(line)
# 'This is one line'
print(str)
# 'This is a second line\nThis is a third line'
使用基本字符串进行测试,how do you do ?
。
line
将得到拆分的第一个元素,str
将得到其余的(因为我们只拆分一次)
我熟悉 split
函数,我会这样使用它:
str = "Line1-abcdef \nLine2-abc \nLine4-abcd"
print str.split( )
上面会return这个:
['Line1-abcdef', 'Line2-abc', 'Line4-abcd']
简单易行。但是,我遇到了一段包含以下语句的代码:
(line, str) = str.split("\n", 1)
这里有两点我不明白:
split
的第二个参数及其作用。我查看了 here,它显示了生成的行数。这是什么意思?split
returns 是一个可迭代的向量。为什么要分配给(line, str)
?这里的(line, str)
是什么意思?
第二个参数maxsplit=1
表示遇到分隔符\n
一次后停止拆分。
因此你只有两部分,你的行和字符串的其余部分。
例如:
str = 'This is one line\nThis is a second line\nThis is a third line'
(line, str) = str.split('\n', 1)
print(line)
# 'This is one line'
print(str)
# 'This is a second line\nThis is a third line'
使用基本字符串进行测试,how do you do ?
。
line
将得到拆分的第一个元素,str
将得到其余的(因为我们只拆分一次)