Stripping \r\n from a line

I want to strip the ending \r\n for a line, examples of the line:

abc \r\n
abc \r
abc \n

I want it to remain as "abc "

what I do now

line=line.strip('\n')
line=line.strip('\r')
line=line.strip('\n')

is there a better way to achieve this?

2 Answers

Use one str.strip() call:

line = line.strip('\r\n')

This removes both characters, in whatever order. The argument to str.strip() is treated as a set of characters, not one longer string:

>>> 'foo bar\r\n\n\r\n\r\n\r\r\r'.strip('\r\n')
'foo bar'

Since you'd expect these lines to only have the characters at the end of each line, you can limit the stripping work to just that side with str.rstrip:

line = line.rstrip('\r\n')
2

If the line is ending with \r\n you can strip-right.

line = line.rstrip(' \r\n')

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like