Python - regex - Splitting string before word

前端 未结 4 2061
悲&欢浪女
悲&欢浪女 2021-01-22 22:21

I am trying to split a string in python before a specific word. For example, I would like to split the following string before \"path:\".

  • split strin
4条回答
  •  既然无缘
    2021-01-22 23:16

    This can be done without regular expressons. Given a string:

    s = "path:bte00250 Alanine, aspartate ... path:bte00330 Arginine and ..."
    

    We can temporarily replace the desired word with a placeholder. The placeholder is a single character, which we use to split by:

    word, placeholder = "path:", "|"
    s = s.replace(word, placeholder).split(placeholder)
    s
    # ['', 'bte00250 Alanine, aspartate ... ', 'bte00330 Arginine and ...']
    

    Now that the string is split, we can rejoin the original word to each sub-string using a list comprehension:

    ["".join([word, i]) for i in s if i]
    # ['path:bte00250 Alanine, aspartate ... ', 'path:bte00330 Arginine and ...']
    

提交回复
热议问题