Omit last item in comma-separated list

I am writing a tag system. The user enters several tags:

abc, def, ghi,

But if they use a trailing comma, the code considers that there are 4 tags, not three.

In my code I write:

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(",")]

In this case, a tag is created. '' How can I change the code to ignore any entry that I suppose len (str) = 0?

+3
source share
7 answers
for tag in tags.split(",") if tag.strip()
+2
source
>>> x = "first, second, third,"
>>> y = [ele for ele in x.split(',') if ele]
>>> y
['first', ' second', ' third']

Using the fact that non-empty strings are returned True.

+3
source

(), :

def f(x): return x != ''

filter( f, tag_list )
+1

lstrip(), strip() ? , abc , def; "abc " ?

(, , ), , :

try: # EAFP
    tags = (tag.strip() for tag in request.POST['tags'].split(','))
    tag_list = [Tag.objects.get_or_create(name = tag)[0] for tag in tags if tag]
    # 'if tag' is the operative "filtering" bit
except KeyError: pass
+1
tag_list = [tag.lstrip() for tag in tags.split(",") if len(tag.lstrip())>0]

tag_list .

.

0

tags , tag.lstrip() get_or_create(name = ...):

if "tags" in request.POST:
    tags = request.POST["tags"]
    tags = (tag.lstrip() for tag in tags.split(',') if tag.strip())
    tag_list = [Tag.objects.get_or_create(name = tag)[0] for tag in tags]
0

, , :

filter(len, map(str.strip, request.POST.getlist("keys")))

.

0

Source: https://habr.com/ru/post/1777329/


All Articles