我的数据库存储了一些标准的地址行字段(地址行1,2 ..城市,国家/地区,邮政编码),我想将它们连接为人类形式。我已经编写了以下代码,但是不确定一堆if语句是否非常有效。 (用python编写,但这是我关心的算法)
def human_readable_address(self):
'''
Return human readable address
If address1 is empyty, return None
'''
addr = ""
if(self.address1):
addr += self.address1 + ", "
else:
return None
if(self.address2):
addr += self.address2 + ", "
if(self.city):
addr += self.city + ", "
if(self.postal_code):
addr += self.postal_code + ", "
if(self.country):
addr += self.country + ", "
return addr
你们怎么看?有更好的方法吗?
答案 0 :(得分:2)
您可以使用str.join()
来代替使用字符串连接(每次都会创建一个新字符串):
def human_readable_address(self):
'''
Return human readable address
If address1 is empty, return None
'''
if not self.address1:
return None
parts = list(filter(None, [self.address1, self.address2, self.city,
self.postal_code, self.country]))
return ', '.join(parts)