tags:

views:

50

answers:

3

Hi here's my code:

keywords_list = """
cow
dog
cat
"""

keywords_list = [i.strip() for i in keywords_list.split("\n") if i]

I'm still getting an empty element(last element) and I'm wondering why. Also suggestions to improve my code would be appreciated.

Thanks in advance!

edit: solved it myself by stripping the string first but I'm still wondering why there's a remaining empty string element in the list.

Here's my solution:

keywords_list = [i.strip() for i in keywords_list.strip().split("\n")]
+2  A: 

You're checking if i, and that succeeds for any non-empty string i -- including one that's all whitespace and so will produce an empty string after stripping. To fix, use

if i and not i.isspace()

as your listcomp's condition (so this only succeeds for non-empty, non-all-whitespace strings).

Alex Martelli
You may infer that I came from PHP programming ;)
+1  A: 

solved it myself by stripping the string first but I'm still wondering why there's a remaining empty string element in the list.

Because your initial string is "\ncow\ndog\ncat\n", so when you split('\n'), you get ['', 'cow', 'dog', 'cat', '']. Its just the way split works - whenever it finds separator, it splits content in 2 elements, one for part before separator, one for part after it, even if one of them is empty.

Daniel Kluev
+1  A: 

When you have a string, 'abc<sep>def<sep>ghi', you clearly want the split to produce ['abc', 'def', 'ghi']. If your string is truncated to 'abc<sep>def<sep>', you still have two separators, so you will still end up with three list items, the last one being the empty string that follows the second separator.

In short, your string uses '\n' as a terminator, but the split function interprets it as a separator.

You can fix this without requiring strip(). Think of '\n' as a separator, and remove the final newline from the input string:

keywords_list = """
cow
dog
cat"""
Marcelo Cantos