How to split a string using an empty separator in Python
Strings are iterables and can be indexed, hence you don't really need to split it at all:
>>> for char in '11111':
... print char
...
1
1
1
1
1
>>> '11111'[4]
'1'
You can "split" it with a call to list, but it doesn't make much difference:
>>> for char in list('11111'):
... print char
...
1
1
1
1
1
>>> list('11111')[4]
'1'
So you only need to do this if your code explicitly expects a list. For example:
>>> list('11111').append('2')
>>> l = list('11111')
>>> l.append(2)
>>> l
['1', '1', '1', '1', '1', 2]
This doesn't work with a straight string:
>>> l.append('2')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'append'
In that case you would need:
>>> l += '2'
>>> l
'111112'
Method #1:
s="Amalraj"
l=[i for i in s]
print(l)
Output:
['A', 'm', 'a', 'l', 'r', 'a', 'j']
Method #2:
s="Amalraj"
l=list(s)
print(l)
Output:
['A', 'm', 'a', 'l', 'r', 'a', 'j']
Method #3:
import re; # importing regular expression module
s="Amalraj"
l=re.findall('.',s)
print(l)
Output:
['A', 'm', 'a', 'l', 'r', 'a', 'j']
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']