Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a string using an empty separator in Python

What is a good way to do some_string.split('') in python? This syntax gives an error:

a = '1111' a.split('')  ValueError: empty separator 

I would like to obtain:

['1', '1', '1', '1'] 
like image 254
Saullo G. P. Castro Avatar asked Jun 29 '13 13:06

Saullo G. P. Castro


People also ask

How do you split a string in Python without spaces?

Use the list() class to split a string into a list of strings. Use a list comprehension to split a string into a list of integers.

How do you split a string by two separators in Python?

To split a string with multiple delimiters in Python, use the re. split() method. The re. split() function splits the string by each occurrence of the pattern.


2 Answers

Use list():

>>> list('1111') ['1', '1', '1', '1'] 

Alternatively, you can use map() (Python 2.7 only):

>>> map(None, '1111') ['1', '1', '1', '1'] 

Time differences:

$ python -m timeit "list('1111')" 1000000 loops, best of 3: 0.483 usec per loop $ python -m timeit "map(None, '1111')" 1000000 loops, best of 3: 0.431 usec per loop 
like image 79
TerryA Avatar answered Oct 01 '22 13:10

TerryA


One can cast strings to list directly

>>> list('1111') ['1', '1', '1', '1'] 

or using list comprehensions

>>> [i for i in '1111'] ['1', '1', '1', '1'] 

second way can be useful if one wants to split strings for substrings more than 1 symbol length

>>> some_string = '12345' >>> [some_string[i:i+2] for i in range(0, len(some_string), 2)] ['12', '34', '5'] 
like image 21
oleg Avatar answered Oct 01 '22 13:10

oleg