Python / Django Concatenating a string depending on whether this string exists

I am creating a property in a Django model called "address". I want the address to consist of concatenating several fields that I have on my model. The problem is that not all instances of this model will have values ​​for all of these fields. So, I want to combine only those fields that have values.

What is the best / most Pythonic way to do this?

Here are the relevant fields from the model:

house = models.IntegerField('House Number', null=True, blank=True)
suf = models.CharField('House Number Suffix', max_length=1, null=True, blank=True)
unit = models.CharField('Address Unit', max_length=7, null=True, blank=True)
stex = models.IntegerField('Address Extention', null=True, blank=True)
stdir = models.CharField('Street Direction', max_length=254, null=True, blank=True)
stnam = models.CharField('Street Name', max_length=30, null=True, blank=True)
stdes = models.CharField('Street Designation', max_length=3, null=True, blank=True)
stdessuf = models.CharField('Street Designation Suffix',max_length=1, null=True, blank=True)

I could just do something like this:

def _get_address(self):
    return "%s %s %s %s %s %s %s %s" % (self.house, self.suf, self.unit, self.stex, self.stdir, self.stname, self.stdes, self.stdessuf)

but then additional gaps will appear as a result.

I could make a series of if statements and merge inside each one, but that seems ugly.

What is the best way to deal with this situation?

Thank.

+5
source
3
parts = (1, 'a', 'b', 2, 'c', 'd', None, 'f')
# parts = (self.house, self.suf, self.unit, 
#           self.stex, self.stdir, self.stname, 
#           self.stdes, self.stdessuf)
' '.join(str(part) for part in parts if part is not None)
# '1 a b 2 c d e f'

comp , - None, , .

+4

, , Falsy, . :

parts = (self.house, self.suf, self.unit, self.stex, self.stdir, self.stname, self.stdes, self.stdessuf)
return " ".join(str(s) for s in parts if s is not None)
+2
" ".join(filter(None, 
               [self.house, self.suf, self.unit, 
                self.stex, self.stdir, self.stname, 
                self.stdes, self.stdessuf]))
+1
source

All Articles