Py学习  »  Python

如何使用Python从数组中找到完整的单词(带空格)?

Roshni Hirani • 4 年前 • 1547 次点击  

我有一个数组,如下所示。我想将用户响应与此数组进行比较。

array = ['finance', 'healthcare', 'information technology', 'government', 'textile', 'petroleum']

这是我的密码。

 if str(user_response) in str(array):
    for j in range(array_length):
        if str(user_response) == str(array[j]):
          some code
 else:
     print("give valid answer")

如果用户的反应是 “信息技术” ,那么它工作得很好。但如果用户的反应是 技术 然后,它也被认为是一个答案。它必须打印 else 用户将给出如下响应时的消息 技术 .

那么,我如何从数组中匹配整个单词“信息技术”,而不是仅匹配“技术”?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/129518
文章 [ 1 ]  |  最新文章 4 年前
AKX
Reply   •   1 楼
AKX    4 年前

你有太多了 str() 向四周施压,使最初的 if 子字符串搜索。

尝试

array = ['finance', 'healthcare', 'information technology', 'government', 'textile', 'petroleum']

user_response = str(...)  # wherever you get the input from

# If you don't cast `array` to a string, 
# Python will just try to find the string in the list; 
# otherwise it does a substring search.

if user_response in array:
   # ...
else:
   print("Give valid answer")