Python如何通过指定字符获取字符串中的单词?

a = "I only want the $1000"

print(get_word_containing("$")

output: $1000

我如何通过该单词中的字符来获取字符串中的整个单词,如上所示?


暮色呼如
浏览 83回答 4
4回答

HUWWW

您的函数可以简单如下:def get_word_containing(string, char):    words = [word for word in string.split() if char in word]    return wordsstring = "I only want the $1000"print(get_word_containing(string, "$"))输出:['$1000']

紫衣仙女

我将稍微修改 @Biplob 函数来打印字符串: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, "$")

人到中年有点甜

import rea = "I only want the $1000"list = re.findall("[$]\w+", text)print(list)上面的代码将为您提供字符串中以 $ 开头的所有单词的数组

Qyouu

import redef 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);所以它会给我们 ['$200', '$1000']
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python