Python 在字典中查找键/值
当我运行此代码时:Python 在字典中查找键/值,python,python-3.x,dictionary,Python,Python 3.x,Dictionary,当我运行此代码时: capitals = {'France': 'Paris', 'Spain': 'Madrid', 'United Kingdom': 'London', 'India': 'New Delhi', 'United States': 'Washington DC','Italy':'Rome', 'Denmark': 'Copenhagen','Germany': 'Berlin','Greece': 'Athens', 'B
capitals = {'France': 'Paris', 'Spain': 'Madrid', 'United Kingdom': 'London',
'India': 'New Delhi', 'United States': 'Washington DC','Italy':'Rome',
'Denmark': 'Copenhagen','Germany': 'Berlin','Greece': 'Athens',
'Bulgaria': 'Sofia','Ireland': 'Dublin','Mexico': 'Mexico City'
}
country = input('Please write a country >>> ')
country = country.title()
if country.isalpha():
if country in capitals:
print(f'The capital of {country} is', capitals.get(country))
else:
print('Sorry, I couldn\'t find this country in my list')
else:
print('There\'s something wrong, please check the country name you\'ve entered')
然后输入“美国”
或“英国”
,返回
请写一个国家>>>英国
有问题,请检查您输入的国家名称
找不到我做错了什么。。。任何人都可以帮我一把吗?问题是
isaplha()
方法考虑了输入字符串“united”和“united kingdom”中的空格,并返回false
。
空格不被视为字母表
您可以尝试以下方法:
if country.replace(" ","").isalpha(): #Removing white spaces
if country in capitals:
print(f'The capital of {country} is', capitals.get(country))
else:
print('Sorry, I couldn\'t find this country in my list')
else:
print('There\'s something wrong, please check the country name you\'ve entered')
这将在检查条件时删除输入字符串中的空格。因为您有空格。空格不被…接受。。。看起来好像是多余的支票。。。只要试着从dict中获取国家/地区,如果它不存在,打印一条消息如果你真的想要,你可以用一个简单的正则表达式进行验证:
if re.match(“[a-zA-Z]+”,country)