Kepala Pening wrote:
> import re
>
> items = []
> for line in open('data.txt'):
> items.append(re.sub('\n', '', line).split(' '))
Hmm. So much to say about so little code!
- the re.sub() is not needed - the split() will remove the trailing newline:
In [53]: 'a b\n'.split()
Out[53]: ['a', 'b']
- you don't need re to replace a fixed character, you can use str.replace():
In [55]: 'a b\n'.replace('\n', '')
Out[55]: 'a b'
- If you just want to strip the trailing newline you can use strip() or
rstrip(), with or without args, depending on how strict you want to be:
In [56]: 'a b\n'.strip()
Out[56]: 'a b'
- It's not clear that the OP wants a list of lines, but if so, a list
comprehension is much more succinct:
items = [ line.split() for line in open('data.txt') ]
would do the job just fine.
Kent
_______________________________________________
Tutor maillist - [email protected]
http://mail.python.org/mailman/listinfo/tutor