【问题标题】:Python: Extract and save string between special characters using a foor loopPython:使用 for 循环在特殊字符之间提取和保存字符串
【发布时间】:2022-08-18 16:12:52
【问题描述】:

我有一个较长的字符串,其中包含用 # 分隔的数字(参见下面的示例)。我想使用 for 循环来存储单个数组中字符之间的数字序列。

#
1 2 3 4 3 8
#
6 9 2 5 7 8
#
2 0 1 6 7 2
#

我该如何继续? 提前致谢!

  • 你试过什么了?这是一个多行字符串吗?
  • 我尝试使用 \'#(.*)#\' 进行 re.search。错误是:\'NoneType\' 对象没有属性 \'group\'

标签: python string substring


【解决方案1】:

普通的旧循环呢?

for line in long_string.split("\n"):
    if line != '#':
        numbers = list(map(int, line.split(" ")))
        print(numbers)

哪个输出:

[1, 2, 3, 4, 3, 8]
[6, 9, 2, 5, 7, 8]
[2, 0, 1, 6, 7, 2]

【讨论】:

    【解决方案2】:

    我们可以在这里使用re.findall 和列表理解:

    inp = """#
    1 2 3 4 3 8
    #
    6 9 2 5 7 8
    #
    2 0 1 6 7 2
    #"""
    
    seq = [[int(x) for x in y.split()] for y in re.findall(r'\d+(?:\s+\d+)*', inp)]
    print(seq)
    
    # [[1, 2, 3, 4, 3, 8], [6, 9, 2, 5, 7, 8], [2, 0, 1, 6, 7, 2]]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-09-02
      • 2022-11-16
      • 2017-11-10
      • 1970-01-01
      • 2021-07-18
      • 2021-03-19
      • 2019-10-13
      相关资源
      最近更新 更多