【问题标题】:How to access the nth line of a multiline variable in python如何在python中访问多行变量的第n行
【发布时间】: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


【解决方案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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      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]

      【讨论】:

        猜你喜欢
        • 2018-01-09
        • 1970-01-01
        • 2017-11-18
        • 1970-01-01
        • 2014-05-02
        • 1970-01-01
        • 2019-07-27
        • 2021-10-18
        • 1970-01-01
        相关资源
        最近更新 更多