Joining multiple strings if they are not empty in Python

前端 未结 3 677
南旧
南旧 2020-12-04 23:17

I have four strings and any of them can be empty. I need to join them into one string with spaces between them. If I use:

new_string = string1 + \' \' + stri         


        
3条回答
  •  心在旅途
    2020-12-04 23:42

    >>> strings = ['foo','','bar','moo']
    >>> ' '.join(filter(None, strings))
    'foo bar moo'
    

    By using None in the filter() call, it removes all falsy elements.

提交回复
热议问题