python - 在 python 3.5 中,如何将字符串变量与另一个字符串的一部分进行比较?

标签 python python-3.5

<分区>

我目前正在学习 Python,我有一个问题也找不到答案,目前我正在尝试获取用户提供的字符串变量并将其与另一个字符串的一部分进行比较。我想要这样的东西:

Program: The given sentence is "I like chemistry", enter a word in the sentence given.

User: like

Program: Your word is in the sentence.

我似乎只能使用 if 函数和 == 来编写程序,但这似乎只能在我输入完整句子时识别出这两个字符串是相似的由程序给出。

从一些答案我已经改变了我的程序,但似乎有一个我找不到的错误。

sentence=("I like chemistry")
print("The given sentence is: ",sentence)
word=input("Give a word in the sentence: ").upper
while word not in sentence:
    word=input("Give a valid word in the sentence: ")
if word in sentence:
    print("valid")

最佳答案

您可以将 insplit 一起使用:

>>> s = "I like chemistry"
>>> words = s.split()
>>> "like" in words
True
>>> "hate" in words
False

这种方法与对非拆分字符串使用 in 的区别如下:

>>> "mist" in s
True
>>> "mist" in words
False

如果您想要任意子字符串,则只需使用 w in s,但如果您想要空格分隔的单词,则使用 w in words

关于python - 在 python 3.5 中,如何将字符串变量与另一个字符串的一部分进行比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37192247/

相关文章:

python - 在 for 循环中使用生成器 send()

python - 检测格式错误的 Accept-Language HTTP header

python - 首次保存时模型字段不会更新

python - Python 存在哪些 SOAP 客户端库,它们的文档在哪里?

python - 将 Python 字典拆分为多个键,将值平均分配

python - 如何找到字典项目中元素最多的列表?

python - 奇怪的异常行为

django - 如何为 Python 3.5 安装 Psycopg2

python - PyQt5 右击 treeWidget 项

Python:在 setter 中使用 getter 或 "private"属性?