I have a source like this
address = ['63-1','STREET APT #3F','','NY']
I wanna this list to string like "63-1 STREET APT #3F NY"
some value in list is often empty. What is the best way to solve it?
I have a source like this
address = ['63-1','STREET APT #3F','','NY']
I wanna this list to string like "63-1 STREET APT #3F NY"
some value in list is often empty. What is the best way to solve it?
Filter out the empty strings, then simply join
by ' '
.
>>> address = ['63-1','STREET APT #3F','','NY']
>>> ' '.join(filter(None, address))
'63-1 STREET APT #3F NY'
filter(None, Iterable)
will filter out all falsy values. In a list of strings, only the empty string is falsy.
I like list comprehensions and generator expressions:
>>> address = ['63-1','STREET APT #3F','','NY']
>>> ' '.join(s for s in address if s)
'63-1 STREET APT #3F NY'
>>> ' '.join([s for s in address if s])
'63-1 STREET APT #3F NY'
But note, that using a list comprehension is the fastest way, as str.join
converts the argument to a list if it isn't already, which adds a layer of overhead for everything other than a list.