我只想将国家和值的首字母大写。
这是我的完整代码:
cities = {
'rotterdam': {
'country': 'netherlands',
'population': 6000000,
'fact': 'is my home town',
},
'orlando': {
'country': 'united states',
'population': 150000000,
'fact': 'is big',
},
'berlin': {
'country': 'germany',
'population': 25000000,
'fact':
'once had a wall splitting west from east (or north from south)',
},
}
for city, extras in cities.items():
print("\nInfo about the city " + city.title() + ":")
for key, value in extras.items():
try:
if extras['country']:
print(key.capitalize() + ": " + value.title())
else:
print(key.capitalize() + ": " + value)
except(TypeError, AttributeError):
print(key.capitalize() + ": " + str(value))
从输出结果来看,这部分已经起作用了,这正是我想要的:
Info about the city Rotterdam:
Country: Netherlands
但我也得到了这个:
Fact: Is My Home Town
如何防止在 ['fact'] 的每个单词都被大写,并仅使键和 ['country'] 值大写使用 .title()?
这样我可以得到:
Info about the city Rotterdam:
Country: Netherlands
Population: 6000000
Fact: Is my home town
Hope that i am clear.
if extras['country']:
改为if key == 'country':
。 - Grant Williamsif extras['country']
只是检查该键是否存在,而不是您当前正在迭代该键。 - Grant Williamskey == ['country']
是将一个str
与一个list
进行比较,而key == 'country'
是将一个str
与另一个str
进行比较。 - Wondercricket