Key Error: "city"

Thomas Jollans tjol at tjol.eu
Sat Sep 9 05:15:45 EDT 2017


On 09/09/17 07:58, V Vishwanathan wrote:
> alert = "Today's forecast for {city}: The temperature will range from{low_temperature} "" to ""{high_temperature}{temperature_unit}Conditions will be {weather_conditions}".format(city,low_temperature,high_temperature,temperature_unit,weather_conditions)

The reason this doesn't (and can't) work is that when you call
"...".format(city, ...), the format method has no idea that you called
the variable "city" rather than something else. You can tell format()
the names of your variables by using keyword arguments:

alert = ("Today's forecast for {city}: The temperature will range from {low_temperature} "
	 " to {high_temperature}{temperature_unit} Conditions will be {weather_conditions}"
	.format(city=city,
	        low_temperature=low_temperature,
		high_temperature=high_temperature,
		temperature_unit=temperature_unit,
		weather_conditions=weather_conditions))

Now that looks a bit silly. It's shorter, but maybe not quite as clear, to not use names at all:

alert = ("Today's forecast for {}: The temperature will range from {} "
	 " to {}{} Conditions will be {}"
	.format(city, low_temperature, high_temperature, temperature_unit, weather_conditions))

If you are using Python 3.6 or newer, there's a third way that, in this case, makes your code far more elegant: a formatted string literal <https://docs.python.org/3/reference/lexical_analysis.html#f-strings>

alert = (f"Today's forecast for {city}: The temperature will range from {low_temperature} "
	 f" to {high_temperature}{temperature_unit} Conditions will be {weather_conditions}")


-- Thomas 




More information about the Python-list mailing list