Search code examples
pythonalgorithmconcatenationstreet-address

Concatenate address lines efficiently


My database stores some standard address lines fields (address line 1,2.. City, Country, Postal/zip code) and I would like to concatenate them to a human form. I've written the following code but I'm not sure if this is very efficient with a bunch of if statements. (Written in python but it's the algorithm that I care about)

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

What do you guys think? Is there a better way?


Solution

  • Instead of using string concatenation (which creates a new string each time) you could use 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]))