作为项目的一部分,我必须能够识别用户输入的关键字.
例如,如果我输入"如何找到伦敦",它会看到伦敦这个词并找到.
我如何使用数组来使代码看起来更干净.
city = [London, Manchester, Birmingham]
where = input("Where are you trying to find")
if(city in where):
print("drive 5 miles")
else:
print("I'm not to sure")
Run Code Online (Sandbox Code Playgroud)
所以我只想知道如何在用户输入中找到数组中的单词.
这不是项目,而是类似的方式.
你走在正确的轨道上.第一个变化是你的字符串文字需要在引号内,例如'London'.其次你有你的in倒退,你应该element in sequence在这种情况下使用它where in cities.
cities = ['London', 'Manchester', 'Birmingham']
where = input("Where are you trying to find")
if where in cities:
print("drive 5 miles")
else:
print("I'm not to sure")
Run Code Online (Sandbox Code Playgroud)
如果要进行子字符串匹配,可以将其更改为
cities = ['London', 'Manchester', 'Birmingham']
where = input("Where are you trying to find")
if any(i in where for i in cities ):
print("drive 5 miles")
else:
print("I'm not to sure")
Run Code Online (Sandbox Code Playgroud)
这可以接受where类似的东西
'I am trying to drive to London'
Run Code Online (Sandbox Code Playgroud)