【问题标题】:How I search all the occurrence of a substring of a string and store the valuenext to that substring to a variable in python?如何搜索字符串的所有出现的子字符串并将该子字符串旁边的值存储到python中的变量中?
【发布时间】:2020-10-22 20:12:25
【问题描述】:

string s1 = "abc:12 Hellow world abc :342 hi there abc :15 在这里,在python中,我想搜索所有'abc'并将值存储在分号之后。更具体地说,如果我搜索'abc' 子字符串,那么12;342;15 值将存储在变量中。

【问题讨论】:

    标签: python string search


    【解决方案1】:

    此正则表达式查找所有abc<optional whitespaces>:<optional whitespace><value>,其中<value> 不得包含空格字符或引号...

    import re
    data = """
    string s1 = "abc:12 Hellow world abc :342 hi there abc :15"
    """
    
    l = re.findall(r'abc\s*:\s*([^\s\"\']+)', data)
    print(l)
    

    l 是您的值列表并保存['12', '342', '15']

    根据您的规范,这不限于数值(如果您的值只能是整数,您可能需要调整正则表达式)

    【讨论】:

      【解决方案2】:

      你可以使用正则表达式:

      import re
      
      string = "abc:12 Hellow world abc :342 hi there abc :15"
      pattern = re.compile(r"abc.*?:(.+?)\b")
      matches = pattern.findall(string)
      
      print(matches) # ['12', '342', '15']
      

      演示:https://regex101.com/r/gAQwVs/1

      【讨论】:

        【解决方案3】:

        试试这个

        根据您的输入!

         a = [int(x.split(" ")[0][1:]) for x in s1.split("abc")[1:]]
         print(a)
        

        输出

         [12, 342, 15]
         
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2023-01-19
          • 2015-10-17
          • 1970-01-01
          • 1970-01-01
          • 2023-03-20
          • 2020-08-25
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多