Consider this code
description = ""
desc = hxs.select('/html/head/meta[2]/@content').extract()
if len(desc) > 0:
description = desc[0]
item["description"] = description
desc is a list of strings. If list is empty description is an empty string, if not it's the first elements from the list. How to make it more pythonic?
Forgot to mention that I have to use 2.7
You can write:
desc = hxs.select("/html/head/meta[2]/@content").extract()
item["description"] = desc[0] if len(desc) > 0 else ""
As pointed out in the comments below, you can also directly evaluate the list in a boolean context:
item["description"] = desc[0] if desc else ""
Alternately you could use make use of the fact that next supports a default
item["description"] = next(iter(desc), "")
You can use exception handling (although it's more verbose than using the conditional expression).
desc = hxs.select('/html/head/meta[2]/@content').extract()
try:
description = desc[0]
except IndexError:
description = ""
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With