You are currently viewing Python Remove a Trailing New Line

How to remove a trailing new line in Python? With rstrip() function, you can easily remove any trailing new lines from your strings, making them easier to work with. In this article, we will learn about the rstrip() method and other methods for removing trailing newlines in Python with examples.

Advertisements

1. Quick Examples of Removing Trailing New Line

These examples will give a high-level overview of methods for removing trailing new lines. We will go through each method in more detail along with examples.


# Quick examples to remove trailing new line

# Initialize string
my_string = "SparkByExamples Provide Tutorials \n"

# Using rstrip() method
text = my_string.rstrip() 

# Using string slicing
text = my_string[:-1] 

# Using strip() method with an argument
text = my_string.strip("\n") 

# Using splitlines() method
text = my_string.splitlines()[0]

2. rstrip() Remove Trailing New Line in Python

One of the simplest and most commonly used methods in Python to remove trailing new lines is to use the rstrip() method. This method removes any whitespace characters from the end of a string, which includes new lines. To remove a trailing newline from a string, simply call the rstrip() method on that string.

It is clear from the name of the rstrip() method, (Right Strip). This method is created for the task of removing whitespaces and new lines at the right side of the text, which means at the end of the lines.

Syntax:


# Syntax of rstrip()
string.rstrip([characters])
  • string: The string from which to remove trailing characters.
  • characters: Optional. A string specifying the set of characters to remove.

If the characters parameter is not specified, rstrip() will remove all whitespace characters, including new lines.


# Python Remove a Trailing New Line
my_string = "SparkByExamples Provide Tutorials \n"
text = my_string.rstrip()
print(text)

# Output: 
# "SparkByExamples Provide Tutorials"

While we can specify the trailing character and it will then remove that specific character:


# Remove specified training character
my_string = "SparkByExamples Provide Tutorials"
text = my_string.rstrip('s')
print(text)

# Output: 
# "SparkByExamples Provide Tutorial"

This will only remove the s character as we have specified it in the parameter. We can also provide a sequence of characters.

3. String Slicing – Remove Trailing New Lines Characters

Another simple way to remove trailing new lines in Python is to use string slicing. String slicing allows you to extract a portion of a string by specifying a range of indices. By specifying the start and end indices of the string, you can easily remove the trailing newline character.

This method only removes a single trailing newline character. If the string contains multiple newline characters at the end you have to use the rstrip() function or any other method from the list.


# Remove single character from the end
my_string = "SparkByExamples Provide Tutorials\n"
text = my_string[:-1]
print(text)

# Output: 
# "SparkByExamples Provide Tutorials"

In the above example, the [:-1] syntax specifies a range of indices that includes all characters of the string except for the last one.

4. strip() – Strip New Line Character

The strip() method is a more general-purpose method for removing characters from the beginning and end of a string. It can be used to remove not only trailing new lines, but also any other specified characters.

Syntax:


# Syntax of strip()
string.strip([chars])

See the below example:


text = my_string.strip()
print(text)

# Output:
# "SparkByExamples Provide Tutorials"

5. splitlines() – Split Newline and Join

Though the splitlines() method is used for splitting a string into a list of lines. It can also be used to remove trailing new lines by splitting a string into lines and then rejoining them without the newline character.

So basically we will first split the string by new lines and then we will use the join() method to join the string. So this new string will contain no new lines character.


# Using splitlines()
lines = my_string.splitlines()
text = ''.join(lines)
print(text)

6. Regular Expression

Regular expressions can be used to match and manipulate patterns of characters in a string, including newline characters. We can create a regular expression that will remove any trailing new lines from the string.

See the following example:


# Using regular expression
import re

my_string = "SparkByExamples Provide Tutorials \n"
text = re.sub(r'\n$', '', my_string)
print(text)

# Output: 
# "SparkByExamples Provide Tutorials"

The endswith() method also acts like a regular expression. It can be used to check whether a string ends with a specified suffix. We can use this method to check whether a string ends with a newline character, and if so, remove it.


if my_string.endswith('\n'):
    text = my_string[:-1]
else:
    text = my_string
print(text)

# Output: 
# "SparkByExamples Provide Tutorials"

7. Summary and Conclusion

We have learned different methods for removing trailing new lines from a string in Python. The method that is specifically designed for this task is rstrip(). However, Python also provided more advanced techniques like regular expressions, Python provides a variety of tools for manipulating text data. Leave questions in the comment section.

Happy Coding!