【问题标题】:how to slice string from specific string in python [duplicate]如何从python中的特定字符串中分割字符串[重复]
【发布时间】:2019-03-15 18:42:12
【问题描述】:

好的,可以说我有

s = 'ABC Here DEF GHI toHere JKL'

我想得到一个只有HeretoHere之间的字符串的新字符串

new_str = 'DEF GHI'

(我不知道在Here 或其他任何地方之前有多少或哪些字符) 我只知道字符串中有HeretoHere。 我怎样才能得到new_str

【问题讨论】:

  • import re;print(re.findall("Here(.*)toHere",target_string)) ...我猜

标签: python


【解决方案1】:

最简单的方法是使用切片:

s[s.find('Here') + len('Here') : s.find('toHere')]
#' DEF GHI '

如果需要,您可以.strip() 关闭结果中的空白区域。

【讨论】:

  • 非常感谢!这就是我一直在寻找的
【解决方案2】:

这可能对使用索引很有用

str1 = 'ABC Here DEF GHI toHere JKL' 
try:
    start=str1.index('Here')+len('Here')
    end=str1.index('toHere')

    print(str1[start:end].strip())
except ValueError:
    print('Either of the substring not found')

【讨论】:

    【解决方案3】:

    您可以使用enumerate.split() 为新切片获取正确的索引,然后使用' '.join() 获取新切片

    s = 'ABC Here DEF GHI toHere JKL'
    s = s.split()
    for i, v in enumerate(s):
        if v == 'Here':
            start = i + 1
        if v == 'toHere':
            end = i
    print(' '.join(s[start:end]))
    # DEF GHI
    

    【讨论】:

      【解决方案4】:

      最简单的方法是使用拆分(恕我直言)

      print(s.split("Here",1)[-1].split("toHere",1)[0])
      

      如果Here 不存在或toHere 不存在,它将无法按您的预期工作(它将遭受与其他解决方案相同的后果)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-12-05
        • 1970-01-01
        • 1970-01-01
        • 2018-03-13
        • 2011-08-19
        • 2019-03-19
        • 1970-01-01
        相关资源
        最近更新 更多