0

I need to read a line from file and strip new line character(s) from the end of the line. The end line can be either LF or CR LF, so I can't just strip the last character. Is there any simple way to do it in python? Or the only way to do it is to check with which ending string ends and strip 1 or 2 characters for LF or CR LF respectively?

sshd
  • 49
  • 1
  • 4

1 Answers1

0

You can use the string.replace() function which will replace anything it finds in the function. You can remove both using the following code where string is your string variable

string.replace('\r', '')
string.replace('\n', '')

You could also put this into a function which takes string as an argument and returns it.

def removeCRLF(string:str)->str: # removeCRLF with type hinting [variable]:[type] and -> [return type]
 return string.replace('\r','').replace('\n','')

This would make calling it on your string similar to this:

newString = removeCRLF(oldString)
Severnarch
  • 84
  • 6
  • This should be unnecessary; modern Python normalizes all line endings to just `\n` unless you go out of your way to avoid that. – tripleee Jun 19 '22 at 12:42
  • There is really no need to reimplement `str. rstrip()`. – BoarGules Jun 19 '22 at 13:09
  • @tripleee You could just remove the parts that remove `\r` if you're completely certain your file has normalized line endings like you said. – Severnarch Jun 19 '22 at 18:25