How to Remove a Trailing Newline in Python
Created
Modified
Using rstrip Method
The str.rstrip()
method returns a copy of the string with trailing characters removed. For example,
#!/usr/bin/python3
s = "\nab c\r\n"
# str.rstrip([chars])
n = s.rstrip()
# n = s.lstrip()
# n = s.strip()
print('{!r}'.format(n))
n = s.rstrip("\n")
print('{!r}'.format(n))
'\nab c' '\nab c\r'
If omitted or None, the chars argument defaults to removing whitespace.
In addition to rstrip()
, there are also the methods strip()
and lstrip()
.
Using regex Module
You can use regex() module to remove a trailing newline, it really simple. For example,
#!/usr/bin/python3
# Import module
import re
s = "\nab c\r\n"
# trailing newline chars
n = re.sub(r'[\n\r]+$', '', s)
print('{!r}'.format(n))
# newline chars everywhere
n = re.sub(r'[\n\r]+', '', s)
print('{!r}'.format(n))
# only 1-2 trailing
n = re.sub(r'[\n\r]{1,2}', '', s)
print('{!r}'.format(n))
'\nab c' 'ab c' 'ab c'
Using translate Method
The str.translate()
method returns a copy of the string in which each character has been mapped through the given translation table.
#!/usr/bin/python3
# Import module
import string
s = "\nab c\r\n"
n = s.translate({ord(c): None for c in string.whitespace})
print('{!r}'.format(n))
'abc'
Using splitlines Method
The str.splitlines()
method returns a list of the lines in the string, breaking at line boundaries.
#!/usr/bin/python3
s = "\nab c\r\n"
n = ''.join(s.splitlines())
# n = ''.join(s.split())
print('{!r}'.format(n))
'ab c'
This method splits on the following line boundaries:
\nLine Feed\rCarriage Return\r\nCarriage Return + Line Feed\v or \x0bLine Tabulation\f or \x0cForm Feed\x1cFile Separator\x1dGroup Separator\x1eRecord Separator\x85Next Line (C1 Control Code)\u2028Line Separator\u2029Paragraph Separator