4 回答

TA貢獻(xiàn)1874條經(jīng)驗(yàn) 獲得超12個(gè)贊
您的函數(shù)可以簡(jiǎn)單如下:
def get_word_containing(string, char):
words = [word for word in string.split() if char in word]
return words
string = "I only want the $1000"
print(get_word_containing(string, "$"))
輸出:
['$1000']

TA貢獻(xiàn)1839條經(jīng)驗(yàn) 獲得超15個(gè)贊
我將稍微修改 @Biplob 函數(shù)來(lái)打印字符串:
def get_word_containing(myStr, char):
for x in myStr.split():
if char in x:
print(x)
mystring = "I only want the $1000"
get_word_containing(mystring, "$")

TA貢獻(xiàn)1895條經(jīng)驗(yàn) 獲得超7個(gè)贊
import re
a = "I only want the $1000"
list = re.findall("[$]\w+", text)
print(list)
上面的代碼將為您提供字符串中以 $ 開(kāi)頭的所有單詞的數(shù)組

TA貢獻(xiàn)1786條經(jīng)驗(yàn) 獲得超11個(gè)贊
import re
def get_word_containing(myStr, char):
list = re.findall("["+char+"]\w+", myStr)
return list;
mystring = "I only $200 want the $1000"
ouput = get_word_containing(mystring, "$")
print(ouput);
所以它會(huì)給我們 ['$200', '$1000']
添加回答
舉報(bào)