I want to strip the ending \r\n for a line, examples of the line:
abc \r\n
abc \r
abc \nI 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')