[Tutor] Tutor Digest, Vol 50, Issue 9

Kent Johnson kent37 at tds.net
Wed Apr 9 16:08:44 CEST 2008

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.


More information about the Tutor mailing list