Search code examples
pythonpython-3.xstringparsingfull-text-indexing

Find n characters after a specific string in Python


I have a webpage's source. It's just a ton of random numbers and letters and function names, saved as a string in python3. I want to find the text that says \"followerCount\": in the source code of this string, but I also want to find a little bit of the text that follows it (n characters). This would hopefully have the piece of text I'm looking for. Can I search for a specific part of a string and the n characters that follow it in python3?


Solution

  • Use .find() to get the position:

    html = "... lots of html source ..."
    position = html.find('"followerCount":')
    

    Then use string slicing to extract that part of the string:

    n = 50 # or however many characters you want
    print(html[position:position+n])