Saturday, August 1, 2009

Python: How to chomp a string

What is the equivalent function of chomp() or chop() at python to remove the newline from the end of any string?

Here is a small piece of code. This will just remove the newline from the hello world string using strip() function.
string = "hello world\n"
string = string.strip() ## chomping or choping the new line
print string

To chomp, you can use regular expression too. Using \s you can do it easily. It will be something like that. Means replacing space with space. But at the end it will eat that new line.

string = re.sub('\s', ' ', string)

1 comment:

Jeff said...


Be careful as strip will remove also the spaces at the beginning.

To just remove the new line at the end, you can use rstrip instead.

Get function name programaticaly - Python

This little piece of code will help you to get the function name programatically. This is very helpful when you are implementing the debug...