Remove end of line python

I'm bubbling up my regular expression based answer from one I posted earlier in the comments of another answer. I think using re is a clearer more explicit solution to this problem than str.rstrip.

>>> import re

If you want to remove one or more trailing newline chars:

>>> re.sub(r'[\n\r]+$', '', '\nx\r\n')
'\nx'

If you want to remove newline chars everywhere (not just trailing):

>>> re.sub(r'[\n\r]+', '', '\nx\r\n')
'x'

If you want to remove only 1-2 trailing newline chars (i.e., \r, \n, \r\n, \n\r, \r\r, \n\n)

>>> re.sub(r'[\n\r]{1,2}$', '', '\nx\r\n\r\n')
'\nx\r'
>>> re.sub(r'[\n\r]{1,2}$', '', '\nx\r\n\r')
'\nx\r'
>>> re.sub(r'[\n\r]{1,2}$', '', '\nx\r\n')
'\nx'

I have a feeling what most people really want here, is to remove just one occurrence of a trailing newline character, either \r\n or \n and nothing more.

>>> re.sub(r'(?:\r\n|\n)$', '', '\nx\n\n', count=1)
'\nx\n'
>>> re.sub(r'(?:\r\n|\n)$', '', '\nx\r\n\r\n', count=1)
'\nx\r\n'
>>> re.sub(r'(?:\r\n|\n)$', '', '\nx\r\n', count=1)
'\nx'
>>> re.sub(r'(?:\r\n|\n)$', '', '\nx\n', count=1)
'\nx'

(The ?: is to create a non-capturing group.)

(By the way this is not what '...'.rstrip('\n', '').rstrip('\r', '') does which may not be clear to others stumbling upon this thread. str.rstrip strips as many of the trailing characters as possible, so a string like foo\n\n\n would result in a false positive of foo whereas you may have wanted to preserve the other newlines after stripping a single trailing one.)

  1. HowTo
  2. Python How-To's
  3. Remove Newline From String in Python

Created: May-09, 2021

  1. Use the strip() Function to Remove a Newline Character From the String in Python
  2. Use the replace() Function to Remove a Newline Character From the String in Python
  3. Use the re.sub() Function to Remove a Newline Character From the String in Python

Strings in Python can be defined as the cluster of Unicode characters enclosed in single or double quotes.

Like other popular programming languages, Python also has a newline character indicated by \n. It is essentially used to trace the culmination of a line and the emergence of a new line in a string.

Newline characters can also be used in f-strings. Moreover, according to the Python documentation, print statements add a newline character at the end of a string by default.

This tutorial will discuss different methods to remove a newline character from a string in Python.

Use the strip() Function to Remove a Newline Character From the String in Python

The strip() function is used to remove both trailing and leading newlines from the string that it is being operated on. It also removes the whitespaces on both sides of the string.

The following code uses the strip() function to remove a newline character from a string in Python.

str1 = "\n Starbucks has the best coffee \n"
newstr = str1.strip()
print(newstr)

Output:

Starbucks has the best coffee

The rstrip() function can be used instead of the strip function if there is only the need to remove trailing newline characters. The leading newline characters are not affected by this function and remain as they are.

The following code uses the rstrip() function to remove a newline character from a string in Python.

str1 = "\n Starbucks has the best coffee \n"
newstr = str1.rstrip()
print(newstr)

Output:


Starbucks has the best coffee

Use the replace() Function to Remove a Newline Character From the String in Python

Also known as the brute force method, It uses the for loop and replace() function. We look for the newline character \n as a string inside a string, and manually replace that from each string with the help of the for loop.

We use a List of strings and implement this method on it. Lists are one of the four built-in datatypes provided in Python and can be utilized to stock multiple items in a single variable.

The following code uses the replace() function to remove a newline character from a string in Python.

list1 = ["Starbucks\n", "has the \nbest", "coffee\n\n "]
rez = []

for x in list1:
    rez.append(x.replace("\n", ""))

print("New list : " + str(rez))

Output:

New list : ['Starbucks', 'has the best', 'coffee ']

Use the re.sub() Function to Remove a Newline Character From the String in Python

The re module needs to import to the python code to use the re.sub() function

The re module is a built-in module in Python, which deals with regular expression. It helps in performing the task of searching for a pattern in a given particular string.

The re.sub() function is essentially used to take a substring and replace its occurrence in the string with another substring.

The following code uses the re.sub() function to remove a newline character from a string in Python.

#import the regex library
import re

list1 = ["Starbucks\n", "has the \nbest", "coffee\n\n "]
  
rez = []
for sub in list1:
    rez.append(sub.replace("\n", ""))
          
print("New List : " + str(rez))

Output:

New List : ['Starbucks', 'has the best', 'coffee ']

Related Article - Python String

  • Remove Commas From String in Python
  • Check a String Is Empty in a Pythonic Way
  • Convert a String to Variable Name in Python
  • Remove Whitespace From a String in Python
  • How do you trim at the end of Python?

    Python Trim String.
    strip(): returns a new string after removing any leading and trailing whitespaces including tabs ( \t )..
    rstrip(): returns a new string with trailing whitespace removed. ... .
    lstrip(): returns a new string with leading whitespace removed, or removing whitespaces from the “left” side of the string..

    How do you remove things from the end of a string?

    There are four ways to remove the last character from a string:.
    Using StringBuffer. deleteCahrAt() Class..
    Using String. substring() Method..
    Using StringUtils. chop() Method..
    Using Regular Expression..

    How do I remove the last substring from a string in Python?

    Given below are a few methods to solve the given task..
    Method #1: Using Naive Method..
    Method #2: Using sub() method..
    Method #3: Using replace() method..

    How do you remove the last 3 of a string in Python?

    Here is an example, that removes the last 3 characters from the following string..
    str = "How are you" modified = str[:-3] print(modified).
    str = "How are you" modified = str. rstrip("you") print(modified) # "How are".
    name = "justin" modified = name. rstrip("stin") # removing last 4 characters print(modified) # "ju".