How can I remove a trailing newline in python?
A trailing new line is a ’\n’ character at the end of a line like that in Python strings. In this article let’s learn how we can remove this trailing newline.
- Using rstrip
- Using strip()
- Using replace()
- Using regex
1. Using strip():
This string method removes the trailing and leading characters which may also have whitespaces from a string.
Example:
string_eg = " Python by i2 tutorials " string_trim = string_eg.strip() print("The Original String:", string_eg) print("String after trimming:", string_trim)
output:
2. Using rstrip():
The rstrip() method removes the trailing characters from a string and returns a copy of this trimmed string.
Example:
string_eg = " Python by i2 tutorials " string_trim = string_eg.rstrip() print("The Original String:", string_eg) print("String after trimming:", string_trim)
output:
3. Using replace():
We check for ’\n’ as a string and replace it using a for loop and replace() method.
Example:
demo_list = ["Python\n", "b\ny", "i2tutorials\n\n"] list_trimmed = [] for x in demo_list: list_trimmed.append(x.replace("\n", "")) print("Original List : " + str(demo_list)) print("Trimmed List : " + str(list_trimmed))
output:
4. Using Regex:
A Regular Expression[RegEx] pattern is a five-letter string that starts with ‘a’ and ends with ‘s’.
^a...s$
We first have to import re module to work with these regular expressions.
Example:
import re string_eg = " Python by i2 tutorials " string_trim = re.sub(r'^\s+$', '', string_eg) print("The Original String:", string_eg) print("String after trimming:", string_trim)
output:
The sub() method performs a global replacement of all the newline characters with an empty string. This method checks for every occurrence of a newline character .
In the regex expression, ^ is known as caret which denotes if a string is starting with a specific character or not. \s denotes a whitespace and | denotes the or operation. $ is known as a dollar which denotes if a string is ending with a specific character or not. +(Plus) symbol matches one or more occurrences of the pattern left to it.
Look at a much simpler example below
Example:
import re demo_list = ["Python\n", "b\ny", "i2tutorials\n\n"] list_trimmed = [] for x in demo_list: list_trimmed.append(re.sub("\n", "")) print("Original List : " + str(demo_list)) print("Trimmed List : " + str(list_trimmed))
output: