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

3

给定一个多行变量

var="""this is line 1
this is line 2
this is line 3
this is line 4"""

我该如何将特定行,比如第2行,赋值给变量?


1
可能与如何将多行字符串拆分成多行?重复。 - Georgy
3个回答

1
>>> 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.


0

在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个字符串。由于索引从0开始,因此您需要使用m-1来访问第m个字符串,例如如果您想要访问第3个元素,则需要使用ans[2]。

0
你可以尝试使用"\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'

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接