我有一个下面给出的数组。我想将用户响应与此数组进行比较。
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
当用户像技术一样给出响应时,它必须打印消息。
那么,如何从数组中匹配整个单词“信息技术”,而不仅仅是“技术”?
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")
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句