如何访问 python 中多行变量的第 n 行

How to access the nth line of a multiline variable in python

给定多行变量

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”字符拆分

>>> 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'

你将在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]

假设您想从多个字符串中取出第 m 个字符串。 m-1 因为索引从 0 开始,所以如果你想访问第三个元素,你将必须执行 ans[2]