1

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?

EddyKim
  • 155
  • 1
  • 14

2 Answers2

4

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.

timgeb
  • 76,762
  • 20
  • 123
  • 145
1

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.

iBug
  • 35,554
  • 7
  • 89
  • 134
  • Interestingly, the second version [is faster](https://stackoverflow.com/a/37782238/3620003). First one looks nicer, though. – timgeb Oct 02 '18 at 06:52
  • 1
    @timgeb Because generators (Python iterators) are slower than list comprehensions (tight C loops). – iBug Oct 02 '18 at 06:53
  • 1
    `join` is also a special case of needing a list anyway. – timgeb Oct 02 '18 at 06:55