2016-01-17 153 views
1

對不起,如果這是重複的,我環顧四周,找不到任何符合我需要的東西。我是一個完整的Python初學者,我想知道是否有一種方法來分析一個字符串來查找使用內置模塊的特定單詞。任何幫助表示讚賞。謝謝。檢查字符串是否包含特定字

+1

我認爲你正在尋找*正則表達式*。 –

+0

不要懷疑,閱讀文檔,尋找教程。 – furas

回答

0

這是一個函數,返回True,如果它可以在字符串中找到一個單詞,並且如果它不能,則返回False

def isWordIn(word, string): 
    return not(string.find(word) == -1) 
1

要檢查是否子是在一個字符串,可以發出

substring in mystring 

演示:

>>> 'raptor' in 'velociraptorjesus' 
True 

這interally調用字符串的__contains__方法。根據您對單詞的定義,您需要一個正則表達式來檢查您的單詞是否被單詞邊界包圍(即\ b)。

>>> import re 
>>> bool(re.search(r'\braptor\b', 'velociraptorjesus')) 
False 
>>> bool(re.search(r'\braptor\b', 'veloci raptor jesus')) 
True 

如果一個單詞的定義是,它是由空格(或沒有)包圍,分割你的字符串:

>>> 'raptor' in 'velociraptorjesus'.split() 
False 
>>> 'raptor' in 'veloci raptor jesus'.split() 
True 

如果一個單詞的定義比較複雜,使用正回顧後和前視,即:

bool(re.search(r'(?<=foo)theword(?=bar)', 'some string')) 

其中foo和bar可以是任何你希望找到的單詞之前和之後。

相關問題