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

3 Answers 3

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']
Sign up to request clarification or add additional context in comments.

3 Comments

ah, thanks a ton dude!
Which also means there's a good chance you don't need to turn it into a list in the first place.
@ThijsvanDien: indeed, although I've seen it is usually done to have a way to manipulate the string char-by-char and then join it back into a string.
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 .

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.