[Tutor] spliting to chars
Mark Kels
Mark.Kels at gmail.com
Sat Oct 2 21:40:20 CEST 2004
On Sat, 02 Oct 2004 21:04:56 +0200, Anna Ravenscroft <revanna at mn.rr.com> wrote:
>
> 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
>
But if I read the string from a file it doesnt work... :-(
>>> a=open("c:\\lol.txt","r")
>>> p=list(a)
>>> print p
['abcdefghijklmnopqrstuvwxyz']
How can I do it on a string from a file ?
More information about the Tutor
mailing list