连接多个字符串(如果它们在Python中不为空) [英] Joining multiple strings if they are not empty in Python

查看:236
本文介绍了连接多个字符串(如果它们在Python中不为空)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有四个字符串,其中任何一个都可以为空.我需要将它们连接成一个字符串,并在它们之间留有空格.如果我使用:

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 + ' ' + string2 + ' ' + string3 + ' ' + string4

如果string1为空,结果将是新字符串开头的空白.另外,如果string2string3为空,则我有三个空格.

The result is a blank space on the beginning of the new string if string1 is empty. Also, I have three blank spaces if string2 and string3 are empty.

当我不需要空格时,如何轻松地将它们加入而没有空格?

How can I easily join them without blank spaces when I don't need them?

推荐答案

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

通过在 filter() 调用中使用None,它将删除所有虚假的元素.

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

这篇关于连接多个字符串(如果它们在Python中不为空)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆