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:\"
.
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 ...']