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?
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.
If you just want to remove the empty string at the end you can use rstrip
before splitting.
>>> my_str.rstrip(';').split(';')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With