【发布时间】:2018-10-02 00:17:47
【问题描述】:
给定一个多行变量
var="""this is line 1
this is line 2
this is line 3
this is line 4"""
如何将特定行(例如第 2 行)分配给变量?
【问题讨论】:
标签: python variables multiline
给定一个多行变量
var="""this is line 1
this is line 2
this is line 3
this is line 4"""
如何将特定行(例如第 2 行)分配给变量?
【问题讨论】:
标签: python variables multiline
>>> 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]
【讨论】: