Home > python > chomp() functionality in Python

chomp() functionality in Python

In Perl there is a function called chomp() which is very useful when reading a text file line by line. It removes the newline character ('\n') at the end of lines. How to do the same thing with Python?

Solution #1

For having the same effect, remove the '\n' from each line:

#!/usr/bin/env python

f = open('test.txt', 'r')
for line in f:
    line = line.replace('\n', '')    # remove '\n' only
    # do something with line
    
f.close()

This will replace the '\n' with an empty string.

Solution #2

There is a function called rstrip() which removes ALL whitespace characters on the right side of a string. This is not entirely the same as the previous because it will remove all whitespace characters on the right side, not only the '\n'. However, if you don’t need those whitespace characters, you can use this solution too.

#!/usr/bin/env python

f = open('test.txt', 'r')
for line in f:
    line = line.rstrip()    # remove ALL whitespaces on the right side, including '\n'
    # do something with line
    
f.close()

Update (20111011): As it was pointed out by John C in the comments, “rstrip() also accepts a string of characters…, so line.rstrip('\n') will remove just trailing newline characters.” More info on rstrip here.

Categories: python Tags: , , ,
  1. October 11, 2010 at 15:27

    You might be interested to know that rstrip() also accepts a string of characters you want to strip out, so line.rstrip("\n") will remove just trailing newline characters.

  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: