给定一个多行变量
var="""this is line 1
this is line 2
this is line 3
this is line 4"""
我该如何将特定行,比如第2行,赋值给变量?
>>> var="""this is line 1
... this is line 2
... this is line 3
... this is line 4"""
>>>
>>> line3 = var.splitlines()[3 - 1]
>>> line3
'this is line 3'
str.splitlines
将您的多行字符串拆分为不同的行。第n
行将位于索引n - 1
.
在n行之间,您将有n-1个换行符。假设您有3行,则有2个换行符。
multiple_lines ="""this is line 1
... this is line 2
... this is line 3
... this is line 4"""
ans=multiple_lines.split(“\n”)[m-1]
>>> a = """this is line1
... this is line2
... this is line3"""
>>> a
'this is line1\nthis is line2\nthis is line3'
>>> a.split("\n")[1]
'this is line2'