python - 有效地连接地址行

标签 python algorithm concatenation street-address

我的数据库存储了一些标准地址行字段(地址行 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

大家怎么看?有没有更好的办法?

最佳答案

您可以使用 str.join() 而不是使用字符串连接(每次都创建一个新字符串) :

def human_readable_address(self):
    '''
    Return human readable address
    If address1 is empty, return None
    '''

    if not self.address1:
        return None

    return ', '.join(filter(None, [self.address1, self.address2, self.city,
                                   self.postal_code, self.country]))

关于python - 有效地连接地址行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52315095/

相关文章:

Python(Enthought)元组/列表特征 : how to access a specific element?

python - 有人有 PyCharm 的 monokai 主题吗?

mysql - 使用 concat 和 filesort 时 mysql 查询速度变慢

python - 类 lambda 回调 NameError

algorithm - 创建包含具有特定显示顺序的其他列表元素的列表

algorithm - 将 (key,value) 数据转换为 csv 格式

algorithm - 确定给定障碍物可以行驶多少点

haskell - haskell中列表的索引列表

javascript - 语法错误: identifier starts immediately after numeric literal - setTimeout or concatenation?

python - 实时更新 pyplot 图表