Friday, September 8, 2023

Python Find if Last Character in String is NewLine \n and Delete it from the String

string = "This is a string ending with new line\n"

print(repr(string), string.rfind("\\n"), repr(string[-1:]))
if string[-1:] == "\n":
    print(string[-1:] == "\n", repr(string))
    string = string[:-1] # OR
    string = string.rstrip('\n')
    print("without new line", repr(string))

With rfind() one gets the index from right of the searched string. If found, delete from string, returning the new value without new line (LF).

Output:

'This is a string ending with new line\n' -1 '\n'
True 'This is a string ending with new line\n'
without new line 'This is a string ending with new line'