如何使Python的"in"运算符仅返回真实单词匹配,而不是子字符串匹配?

2024-09-27 00:11:31 发布

您现在位置:Python中文网/ 问答频道 /正文

以下是所需的输出:

"bacillus thurungensis" in "bacillus thurungensis"
TRUE

"bacillus thurungensis" in "Sentence containing bacillus thurungensis."
TRUE

"bacillus thurungensis" in "Subspecies bacillus thurungensis34"
FALSE

"bacillus thurungensis" in "bacillus thurungensis, bacillus genus"
TRUE

"bacillus thurungensis" in "Notbacillus thurungensis, must match word"
FALSE

Python通常认为任何子字符串匹配都是好的,但我不想这样。我希望某些regex或match运算符仅当且仅当它将查询视为主题中的一个单独单词而不仅仅是子字符串时才会生成true。这怎么可能实现呢?在


Tags: 字符串infalsetruematchsentencewordcontaining
1条回答
网友
1楼 · 发布于 2024-09-27 00:11:31

您可以改用regex:

re.match(r"\bbacillus thurungensis\b", "bacillus thurungensis")
re.match(r"\bbacillus thurungensis\b", "Sentence containing bacillus thurungensis.")
re.match(r"\bbacillus thurungensis\b", "Subspecies bacillus thurungensis34")

等等。在

\b是一个word boundary。还要注意字符串r"..."r的用法。在

如果要反复使用regex,也可以使用compile

^{pr2}$

相关问题 更多 >

    热门问题