Chop off text when it reaches certain word in Python

147 Views Asked by At

I'm using Python and I have an HTML-code which I want to chop off as soon as it reaches the word "toc", but I can't figure out how to do, anyone having some nice ideas?

2

There are 2 best solutions below

1
jedwards On BEST ANSWER

Without more information, something like the following works

s = "some string toc remainder of string"

s = s[:s.find('toc')]

print s  # some string

But be aware that this will catch words like "stock" -- so there's likely a better approach depending on your specifics.

0
Mazdak On

You can just use split :

>>> s="""<html lang="en" dir="ltr" class="client-nojs"> <head> <meta charset="UTF-8" /> <title>IBM - Wikipedia, the free encyclopedia</title> <meta name="generator" content="MediaWiki 1.25wmf19" />"""
>>> s.split('UTF')[0]
'<html lang="en" dir="ltr" class="client-nojs"> <head> <meta charset="'