[Tutor] spliting to chars

Anna Ravenscroft revanna at mn.rr.com
Sat Oct 2 21:04:56 CEST 2004


Mark Kels wrote:
> How can I split a string like "abcd efgh ijklmnop" to chars ("a","b","c", etc) ?
> I know It can be done using regular expression, but I have'nt learned
> how to use them...
> 

If you're just looking for a list of all the items, including the 
spaces, you can do it very simply:

 >>> mystring = "abcd efgh ijklmnop"
 >>> mylist = list(mystring)
 >>> print mylist
['a', 'b', 'c', 'd', ' ', 'e', 'f', 'g', 'h', ' ', 'i', 'j', 'k', 'l', 
'm', 'n', 'o', 'p']

If you want to get the characters without the spaces, you could do it 
with a conditional list comprehension:

 >>> mychars = [char for char in mystring if char != ' ']
 >>> print mychars
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 
'o', 'p']
 >>>

HTH,
Anna


More information about the Tutor mailing list