You are using a raw string literal.
r'\n'
is not the newline character, it's a string of length two containing the characters "\" and "n".
>>> r'\n'
'\\n'
>>> len(r'\n')
2
Otherwise, your original approach works (almost) fine.
>>> file_stuff = ['John Smith\n', '\n', 'Gardener\n', '\n', 'Age 27\n', '\n', 'Englishman']
>>> [x.replace('\n', '') for x in file_stuff]
['John Smith', '', 'Gardener', '', 'Age 27', '', 'Englishman']
We can filter out the empty strings like this:
>>> file_stuff = ['John Smith\n', '\n', 'Gardener\n', '\n', 'Age 27\n', '\n', 'Englishman']
>>> no_newline = (x.replace('\n', '') for x in file_stuff)
>>> result = [x for x in no_newline if x]
>>> result
['John Smith', 'Gardener', 'Age 27', 'Englishman']
where no_newline
is a memory efficient generator that does not build an intermediary temporary list.
If you just want to strip whitespace and newline-characters from the beginning and end of your strings, consider the str.strip
method.
>>> file_stuff = ['John Smith\n', '\n', 'Gardener\n', '\n', 'Age 27\n', '\n', 'Englishman']
>>> no_newline = (x.strip() for x in file_stuff)
>>> result = [x for x in no_newline if x]
>>> result
['John Smith', 'Gardener', 'Age 27', 'Englishman']
This could be shortened to
>>> result = [x.strip() for x in file_stuff if x.strip()]
>>> result
['John Smith', 'Gardener', 'Age 27', 'Englishman']
if you can deal with the inelegancy of calling str.strip
twice per string.