Python - 检查一个单词是否在字符串中

时间:2020-12-26 17:00:24

标签: python python-3.x string

如何判断一个词是否在字符串中?

  • 单词不是子字符串。
  • 我不想使用正则表达式。

仅使用 in 是不够的...

类似于:

>>> wordSearch('sea', 'Do seahorses live in reefs?')
False
>>> wordSearch('sea', 'Seahorses live in the open sea.')
True

2 个答案:

答案 0 :(得分:2)

如何拆分字符串和剥离单词标点符号,而不忘记大小写?

w in [ws.strip(',.?!') for ws in p.split()]

也许是这样:

def wordSearch(word, phrase):
    punctuation = ',.?!'
    return word in [words.strip(punctuation) for words in phrase.split()]

    # Attention about punctuation (here ,.?!) and about split characters (here default space)

示例:

>>> print(wordSearch('Sea'.lower(), 'Do seahorses live in reefs?'.lower()))
False
>>> print(wordSearch('Sea'.lower(), 'Seahorses live in the open sea.'.lower()))
True

我把大小写转换移到了函数调用中以简化代码...
而且我没有检查表演。

答案 1 :(得分:1)

使用 in 关键字:

像这样:

print('Sea'in 'Seahorses live in the open sea.')

如果您不希望它区分大小写。将所有字符串转换为 lowerupper

像这样:

string1 = 'allow'
string2 = 'Seahorses live in the open sea Allow.'

print(string1.lower() in string2.lower())

或者您可以像这样使用 find 方法:

string1 = 'Allow'
string2 = 'Seahorses live in the open sea Allow.'

if string2.find(string1) !=-1 :
    print('yes')

如果你想匹配确切的词:

string1 = 'Seah'
string2 = 'Seahorses live in the open sea Allow.'

a = sum([1 for x in string2.split(' ') if x == string1])

if a > 0:
    print('Yes')

else:
    print('No')

更新

你需要忽略所有标点符号,所以使用这个。

def find(string1, string2):
    lst = string2.split(' ')
    puctuation = [',', '.', '!']
    lst2 = []
    
    for x in lst:
        for y in puctuation:
            if y in x[-1]:
                lst2.append(x.replace(y, ''))
        lst2.append(x)
    
    lst2.pop(-1)    
    a = sum([1 for x in lst2 if x.lower() == string1.lower()])
    if a > 0:
        print('Yes')
    
    else:
        print('No')

find('sea', 'Seahorses live in the open sea. .hello!')
相关问题