It sounds like you want something like the Perl chomp()
function.
That's trivial to do in Python:
def chomp(s):
return s[:-1] if s.endswith('\n') else s
... assuming you're using Python 2.6 or later. Otherwise just use the slightly
more verbose:
def chomp(s):
if s.endwith('\n'):
return s[:-1]
else:
return s
If you want to remove all new lines from the end of a string (in the odd case where one might have multiple trailing newlines for some reason):
def chomps(s):
return s.rstrip('\n')
Obviously you should never see such a string returned by any normal Python file object's readline()
nor readlines()
methods.
I've seen people blindly remove the last characters (using s[:-1]
slicing) from the results of file readline()
and similar functions. This is a bad idea because it can lead to an error on the last line of the file (in the case where a file ends with anything other than a newline).
At first you might be lulled into a false sense of security when blindly stripping final characters off lines you've read. If you use a normal text editor to create your test suite files you'll have a newline silently added to the end of the last line by most of them. To create a valid test file use code something like:
f = open('sometest.txt', 'w')
f.write('some text')
f.close()
... and then if you re-open that file and use the readline()
or readlines()
file methods on it you'll find that the text is read without the trailing newline.
This failure to account for text files ending in non-newline characters has plagued many UNIX utilities and scripting languages for many years. It's a stupid corner base bug that creeps into code just often enough to be a pest but not often enough for people to learn from it. We could argue that "text" files without the ultimate newline are "corrupt" or non-standard; and that may be valid for some programming specifications.
However, it's all too easy to ignore corner cases in our coding and have that ignorance bite people who are depending on your code later. As my wife says: when it comes to programming ... practice safe hex!