Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split function - avoid last empty space

Tags:

python

split

I have a doubt on how to use the split function.

str = 'James;Joseph;Arun;'
str.split(';')

I got the result ['James', 'Joseph', 'Arun', '']

I need the output as ['James', 'Joseph', 'Arun']

What is the best way to do it?

like image 876
Jisson Avatar asked May 28 '12 06:05

Jisson


1 Answers

To remove all empty strings you can use a list comprehension:

>>> [x for x in my_str.split(';') if x]

Or the filter/bool trick:

>>> filter(bool, my_str.split(';'))

Note that this will also remove empty strings at the start or in the middle of the list, not just at the end.

  • Remove empty strings from a list of strings

If you just want to remove the empty string at the end you can use rstrip before splitting.

>>> my_str.rstrip(';').split(';')
like image 169
Mark Byers Avatar answered Oct 09 '22 11:10

Mark Byers