![](/img/trans.png)
[英]How would a range work if the starting point and ending points are the same in Python
[英]How to find a substring of text with a known starting point but unknown ending point in python
我有一長串文字。 我想使用關鍵字在某個點壓縮該字符串,以指示我在 Python 中的新字符串的開始。 例如,我的字符串是:
“你好,我叫約翰。我今年二十五歲。我住在紐約市。我在華爾街工作。” 我想要從“紐約”到文本末尾的文本,即我需要代碼來提取 substring“紐約市。我在華爾街工作。”
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"
任何幫助將非常感激!
我相信最好的方法是使用正則表達式:
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.'
這樣做是搜索您的 key_phrase,以及關鍵字在字符串中開始的索引 position。 然后它使用索引從原始字符串中 key_phrase 開始的位置創建新字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.