Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to split a concatenated string into a tuple and ignore empty strings

Tags:

python

split

I have a concatenated string like this:

my_str = 'str1;str2;str3;'

and I would like to apply split function to it and then convert the resulted list to a tuple, and get rid of any empty string resulted from the split (notice the last ';' in the end)

So far, I am doing this:

tuple(filter(None, my_str.split(';')))

Is there any more efficient (in terms of speed and space) way to do it?

like image 675
MLister Avatar asked Jun 12 '12 16:06

MLister


People also ask

How do I split a string into a tuple?

When it is required to convert a string into a tuple, the 'map' method, the 'tuple' method, the 'int' method, and the 'split' method can be used. The map function applies a given function/operation to every item in an iterable (such as list, tuple). It returns a list as the result.

How do I remove an empty string from a tuple in Python?

Python3. Method 2: Using the filter() method Using the inbuilt method filter() in Python, we can filter out the empty elements by passing the None as the parameter.

What is the best way to split a string in Python?

The split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.

How do you split a string into multiple lines in Python?

Use triple quotes to create a multiline string It is the simplest method to let a long string split into different lines. You will need to enclose it with a pair of Triple quotes, one at the start and second in the end.


2 Answers

How about this?

tuple(my_str.split(';')[:-1])
('str1', 'str2', 'str3')

You split the string at the ; character, and pass all off the substrings (except the last one, the empty string) to tuple to create the result tuple.

like image 186
Levon Avatar answered Oct 22 '22 23:10

Levon


That is a very reasonable way to do it. Some alternatives:

  • foo.strip(";").split(";") (if there won't be any empty slices inside the string)
  • [ x.strip() for x in foo.split(";") if x.strip() ] (to strip whitespace from each slice)

The "fastest" way to do this will depend on a lot of things… but you can easily experiment with ipython's %timeit:

In [1]: foo = "1;2;3;4;"

In [2]: %timeit foo.strip(";").split(";")
1000000 loops, best of 3: 1.03 us per loop

In [3]: %timeit filter(None, foo.split(';'))
1000000 loops, best of 3: 1.55 us per loop
like image 22
David Wolever Avatar answered Oct 23 '22 00:10

David Wolever