Remove newline characters from string in Python

In this article, we will discuss different ways to delete all newline characters from a string in Python.

Table of Contents

Remove newline characters from string using Regex

In Python, the regex module provides a function to replace the contents of a string based on a matching regex pattern. The signature of function is like this,

sub(pattern, replacement_str, original_str)

It looks for the matches of the given regex pattern in the sting original_str and replaces all occurrences of matches with the string replacement_str.

To delete all the newline characters from a string, we can pass a regex pattern that matches all the newline characters in string i.e. “[\n|\r|\r\n]” and replace them with empty strings.

For example,

import re

strValue = "This \n a \n sample \r\n string \n !"

# Regext pattern to match all newline characters
pattern = "[\n|\r|\r\n]"

# Delete all newline characters from string
strValue = re.sub(pattern, '', strValue )

print(strValue)

Output:

This  a  sample  string  !

It deleted all the newline characters from string in Python.

Remove newline characters from string using replace() function

In Python, the string class provides a member function to replace all occurrences of a substring in a string i.e.

str.replace(to_be_replaced, replacement, count )

It accepts two arguments i.e.

  • to_be_replaced : The string to be replaced.
  • replacement : The replacement string.
  • count : The number of times sub-string will be replaced with the replacement string.

It returns a copy of the calling string object but with the changed contents i.e. after replacing all the occurrences of sub-string in that string. The original string remains unchanged.

To delete all the newline characters from a string, replace all occurrences of ‘\n’ and ‘\r’ in string with an empty string.

For example,

strValue = "This \n a \n sample \r\n string \n !"

newLineChars = "\r\n"

# Remove all occurrences of character newline
# characters from string.
for ch in newLineChars:
    strValue = strValue.replace(ch, '')

print(strValue)

Output:

This  a  sample  string  !

It deleted all the newline characters from string in Python.

Remove newline characters from string using translate()

In Python, the string class provides a member function translate(). It accepts a translation table as an argument and replaces the characters in a string based on the mapping in the translation table.

We can use the maketrans() function to create this mapping in the form of a translation table. If we want to just delete some characters instead of replacement, then we can provide those characters as a third argument.

To delete all the newline characters from a string, create a translation table where characters ‘\r’ and ‘\n’ are mapped with empty strings.

For example,

strValue = "This \n a \n sample \r\n string \n !"

# Map characters to be deleted with an empty string
translation_table = str.maketrans('', '', "\r\n")

# Remove specific characters from the string based
# on translation table / mapping table
strValue = strValue.translate(translation_table)

print(strValue)

Output:

This  a  sample  string  !

It deleted all the newline characters from string in Python.

Remove newline characters from string using filter() & join()

In Python, you can use the filter() function to filter all the occurrences of certain characters from a string. The steps are as follows,

  • Create a lambda function that accepts a character as an argument and returns True if the passed character matches the condition.
  • Pass this lambda function as the conditional argument to filter() function along with the string to be modified.
  • The filter() function iterates over all characters of string and yields only those characters for which lambda function returns True i.e. all characters except the character to be deleted.
  • Use join() function to combine all yeilded characters returned by filter() function.

This way, we can filter out some characters from the string based on conditions.

To delete all the newline characters from a string, filters the characters ‘\r’ and ‘\n’ using filter() function and a lambda function. Then join the remaining characters.

For example,

strValue = "This \n a \n sample \r\n string \n !"

charsToBeDeleted = "\r\n"

# Filter all newline characters in string and create list of remaining chars
filtered_chars = filter(lambda item: item not in charsToBeDeleted,
                        strValue)

# Join characters in the filtered list
strValue = ''.join(filtered_chars)

print(strValue)

Output:

This  a  sample  string  !

It deleted all the newline characters from string in Python.

Summary:

We learned about four different ways to delete all newline characters from a string in Python.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top