迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 > Python >

在 Python 中检查字符串中是否存在单词

作者:迹忆客 最近更新:2023/04/24 浏览次数:

假设存在一个字符串“The weather is so pleasant today”。 如果我们想检查字符串中是否存在单词“weather”,我们有多种方法可以查明。

在本指南中,我们将了解 in 运算符、string.find() 方法、string.index() 方法和正则表达式 (RegEx)。


在 Python 中使用 in 运算符检查字符串中是否存在单词

在字符串或序列(如列表、元组或数组)中搜索单词的最简单方法之一是通过 in 运算符。 它在条件中使用时返回一个布尔值。

它可以是真也可以是假。 如果指定的词存在,则该语句的计算结果为真; 如果该词不存在,则计算结果为 false。

此运算符区分大小写。 如果我们尝试在以下代码中定位单词 Fun,我们将在输出中获得消息 Fun not found。

示例代码:

#Python 3.x
sentence = "Learning Python is fun"
word = "fun"
if word in sentence:
    print(word, "found!")
else:
    print(word, "not found!")

输出:

fun found!

如果我们想在字符串中检查单词而不用担心大小写,我们必须将主字符串和要搜索的单词转换为小写。 在下面的代码中,我们将检查单词 Fun。

示例代码:

#Python 3.x
sentence = "Learning Python is fun"
word = "Fun"
if word.lower() in sentence.lower():
    print(word, "found!")
else:
    print(word, "not found!")

输出

Fun found!

在 Python 中使用 String.find() 方法检查字符串中是否存在单词

我们可以使用带有字符串的 find() 方法来检查特定单词。 如果指定的单词存在,它将返回该单词在主字符串中的最左边或起始索引。

否则,它只会返回索引 –1。 find() 方法还计算空格的索引。 在下面的代码中,我们得到了输出 9,因为 9 是 Python 的起始索引,即字符 P 的索引。

默认情况下,此方法也区分大小写。 如果我们检查单词 python,它将返回 -1。

示例代码:

#Python 3.x
string = "Learning Python is fun"
index=string.find("Python")
print(index)

输出:

9

在 Python 中使用 String.index() 方法检查字符串中是否存在单词

index() 与 find() 方法相同。 此方法还返回主字符串中子字符串的最低索引。

唯一的区别是,当指定的单词或子字符串不存在时,find() 方法返回索引 –1,而 index() 方法抛出异常(值错误异常)。

示例代码:

#Python 3.x
mystring = "Learning Python is fun"
print(mystring.index("Python"))

输出:

9

现在我们尝试找到句子中不存在的单词。

#Python 3.x
mystring = "Learning Python is fun"
print(mystring.index("Java"))

输出:

Python 中使用 String.index() ValueError


在 Python 中使用 search() 方法检查字符串中是否存在单词

我们可以通过 search() 方法通过字符串的模式匹配来检查特定的单词。 这个方法在 re 模块中可用。

这里的 re 代表正则表达式。 搜索方法接受两个参数。

第一个参数是要查找的单词,第二个参数是整个字符串。 但是这种方法比其他方法慢。

示例代码:

#Python 3.x
from re import search
sentence = "Learning Python is fun"
word = "Python"
if search(word, sentence):
    print(word, "found!")
else:

    print(word, "not found!")

输出:

Python found!

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Pandas read_csv()函数

发布时间:2024/04/24 浏览次数:254 分类:Python

Pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 DataFrame 中。

Pandas 追加数据到 CSV 中

发布时间:2024/04/24 浏览次数:352 分类:Python

本教程演示了如何在追加模式下使用 to_csv()向现有的 CSV 文件添加数据。

Pandas 多列合并

发布时间:2024/04/24 浏览次数:628 分类:Python

本教程介绍了如何在 Pandas 中使用 DataFrame.merge()方法合并两个 DataFrames。

Pandas loc vs iloc

发布时间:2024/04/24 浏览次数:837 分类:Python

本教程介绍了如何使用 Python 中的 loc 和 iloc 从 Pandas DataFrame 中过滤数据。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便