[Django]-Omit last element in comma-separated list

2πŸ‘

βœ…

for tag in tags.split(",") if tag.strip()

3πŸ‘

>>> x = "first, second, third,"
>>> y = [ele for ele in x.split(',') if ele]
>>> y
['first', ' second', ' third']

Using the fact that non empty strings return True.

1πŸ‘

Use filter(), like so:

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

filter( f, tag_list )

1πŸ‘

Do you really want to use lstrip() rather than strip() for processing the tags? What if the user enters abc , def; do you really want to allow a tag "abc " with a trailing space?

If you really want to strip the tags on both sides (which I think you do), then it’s a simple matter of doing that and then omitting the empty ones:

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

0πŸ‘

tag_list = [tag.lstrip() for tag in tags.split(",") if len(tag.lstrip())>0]

will generate the tag_list without the empty character.

Rest should be simple.

0πŸ‘

You could do all your tags processing in once place, so you don’t have to
call tag.lstrip() inside 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πŸ‘

If your tags are actually set individually in the same variable instead of as a string list you have the option of just writing:

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

Without having to parse a string list manually.

Leave a comment