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']
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.
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.
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
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']
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