Search code examples
pythonstringlistsplitstrip

Last element in python list, created by splitting a string is empty


So I have a string which I need to parse. The string contains a number of words, separated by a hyphen (-). The string also ends with a hyphen.

For example one-two-three-.

Now, if I want to look at the words on their own, I split up the string to a list.

wordstring = "one-two-three-"
wordlist = wordstring.split('-')

for i in range(0, len(wordlist)):
     print(wordlist[i])

Output

one
two
three
#empty element

What I don't understand is, why in the resulting list, the final element is an empty string. How can I omit this empty element?

Should I simply truncate the list or is there a better way to split the string?


Solution

  • You have an empty string because the split on the last - character produces an empty string on the RHS. You can strip all '-' characters from the string before splitting:

    wordlist = wordstring.strip('-').split('-')