[Tutor] spliting to chars

Anna Ravenscroft revanna at mn.rr.com
Sat Oct 2 22:16:36 CEST 2004


Mark Kels wrote:
> 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 ?
> 

 >>> a=open('C:\\..\\mystringfile.txt')
 >>> s = a.read()
 >>> print s
abcd efgh ijklmnop

 >>> ls = list(s)
 >>> print ls
['a', 'b', 'c', 'd', ' ', 'e', 'f', 'g', 'h', ' ', 'i', 'j', 'k', 'l', 
'm', 'n', 'o', 'p', '\n']
 >>> a.close()
 >>>

You need to explicitly use file.read() to read it in as a string. If you 
want to immediately go for a list, you can do this instead if you want:

 >>> a=open('C:\\..\\mystringfile.txt')
 >>> la = list(a.read())
 >>> print la
['a', 'b', 'c', 'd', ' ', 'e', 'f', 'g', 'h', ' ', 'i', 'j', 'k', 'l', 
'm', 'n', 'o', 'p', '\n']
 >>> a.close()
 >>>

This all assumes that your purpose isn't really trying to read the file 
character by character to process each character one at a time, and that 
you don't have some huge file that'll slow everything to a crawl and 
overrun your memory by reading the whole thing in as one string...

Anna


More information about the Tutor mailing list