Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to find a substring of text with a known starting point but unknown ending point in python

I have a long string of text. I want to condense that string at a certain point using a key word to indicate the start of my new string in Python. For example, my string is:

"Hello my name John. I am twenty-five years old. I live in New York City. I work on Wall Street." I want the text from "New York" to the end of the text i.e. I need code to pull the substring "New York City. I work on Wall Street."

have = "Hello my name John. I am twenty-five years old. I live in New York City. I work on Wall Street."
want = "New York City. I work on Wall Street."
key_phrase = "New York"

Any help would be much appreciated!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I believe the best way to do this would be with regex:

import re

have = "Hello my name John. I am twenty-five years old. I live in New York City. I work on Wall Street."
want = "New York City. I work on Wall Street."
key_phrase = "New York"

key_phrase_begins = re.search(key_phrase, have).span()[0]
new_string = have[key_phrase_begins:]
print(new_string) # Outputs: 'New York City. I work on Wall Street.'

What this is doing is searching for your key_phrase, and the index position at which the key phrase begins within the string. Then it is using indexing to create the new string from where the key_phrase begins in the original string.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading