[Tutor] spliting to chars

Bill Mill bill.mill at gmail.com
Sat Oct 2 21:08:41 CEST 2004


Mark,

What anna said was right on point.

I wanted to add that if you just want to iterate over the chars in the
sequence, that is trivial too:

for ch in mystring:
    do_something(ch)

Peace
Bill Mill


On Sat, 02 Oct 2004 21:04:56 +0200, Anna Ravenscroft <revanna at mn.rr.com> wrote:
> 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
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>


More information about the Tutor mailing list