【问题标题】:Returning the part of a string that is found before the first blank line in the string in Python返回在 Python 中字符串的第一个空行之前找到的字符串部分
【发布时间】:2018-11-16 07:37:09
【问题描述】:

我有一个分配了空行的字符串,我需要返回在它的第一个空行之前找到的那个字符串的块。 例如:

aaaaa
bbbb
1223

212
fff

返回的字符串应该是:

aaaaa
bbbb
1223

注意:我使用的是 Python 2.7

【问题讨论】:

  • split on \n\n 或任何行分隔符 加倍 并获取 0-index 元素。

标签: python string python-2.7


【解决方案1】:
def find(string):
    return string[:string.find('\n\n')]

【讨论】:

  • 签出this post 你也可以试试:return string[1:string.find('\n\n')]
【解决方案2】:

这是一种方法。使用简单的迭代。

演示:

res = []
with open(filename, "r") as infile:
    for line in infile:
        if not line.strip():
            break
        else:
            res.append(line)
print( "".join(res) )

【讨论】:

  • 为什么是" ".join 而不是"".join
猜你喜欢
  • 1970-01-01
  • 2013-05-04
  • 1970-01-01
  • 2018-11-21
  • 1970-01-01
  • 2023-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多