0

I want to be able to split a string that just contains letters into separate letters. From the code I have below; I expected the variable f to contain ['a','b'] but it did not. Any ideas as to how I might fix this problem?

a = "bc"
f = a.split()
print(f)

output:

['bc']
Paul Panzer
  • 51,835
  • 3
  • 54
  • 99
Mental
  • 33
  • 6

3 Answers3

5

In that case you do not have to split: a string is iterable over its characters, so you can simply use:

f = list(a)

This will construct a list such that every character in the string is an element in the resulting list:

>>> a="foobar"
>>> f=list(a)
>>> f
['f', 'o', 'o', 'b', 'a', 'r']
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
1

If you try by direction iteration then:

x=[i for i in a]

now analyzing its time with respect to that for list(a);

tarptaeya@TARPTAEYA:~$ python -m timeit "a='foobar';x=[i for i in a]"
1000000 loops, best of 3: 0.443 usec per loop
tarptaeya@TARPTAEYA:~$ python -m timeit "a='foobar';list(a)"
1000000 loops, best of 3: 0.385 usec per loop

hence splitting using list() method is more efficient method compared to first .

Anmol Gautam
  • 949
  • 1
  • 12
  • 27
0

If you want to get only letter.

>>> val = 'abcdefg 12'
>>> [item for item in list(val) if item.isalpha()]
['a', 'b', 'c', 'd', 'e', 'f', 'g']

Another solution:

>>> filter(lambda x: x.isalpha(), list(val))
['a', 'b', 'c', 'd', 'e', 'f', 'g']
Adem Öztaş
  • 20,457
  • 4
  • 34
  • 42