我如何使用 python 在字符串中找到确切的字符串

How do i find an exact string within a string using python

使用简单的 "if "blank" in string" 语句我想在 csv 列中找到一个确切的词。

with open("example.csv","r") as file
reader=csv.reader(file)

string=""

for row in reader:
    if "Hello" in row[0]:
        string+=row[0]

print(string)

如果 csv 在行 [0] 中有 "Hello World" 字符串将等于 "Hello World" 但我只希望字符串为 +=row[0] 如果特别是 "Hello" 在行[ 0] 没有 "World"。

总而言之,我希望代码不打印任何内容,除非恰好 "Hello" 在行 [0] 中。

您可以使用 ==:

检查一个字符串是否与另一个字符串完全相同

if row[0] == "Hello":

这将为您找到具有精确值的所有行。如果您正在寻找字符串的 部分 ,您应该只使用 in

如果你想在 "Hello" 是字符串的一部分时查找它,但后面跟着 "World" 时除外,那么你可以尝试

if "Hello" in row[0] and not "Hello World" in row[0]:

对于更复杂的内容,您需要查看 regular expressions