在逗号分隔列表中省略最后一个元素
我正在写一个标签系统。用户可以输入多个标签:
abc, def, ghi,
但是如果他们在最后加了一个逗号,代码就会认为有四个标签,而不是三个。
在我的代码中,我写了:
if "tags" in request.POST:
tags = request.POST["tags"]
tag_list = [Tag.objects.get_or_create(name = tag.lstrip())[0] for tag in tags.split(",")]
在这种情况下,会创建一个空标签 ' '。我该怎么改代码,让它忽略任何长度为0的输入呢?
7 个回答
1
使用 filter() 函数,像这样:
def f(x): return x != ''
filter( f, tag_list )
3
>>> x = "first, second, third,"
>>> y = [ele for ele in x.split(',') if ele]
>>> y
['first', ' second', ' third']
利用非空字符串会返回 True
这一点。
2
for tag in tags.split(",") if tag.strip()
当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。