Python Remove Newline from List

🎯 Objective: In this article, we will discuss the methods to remove \n or newline characters from a list.

Introduction

In a string, the ‘\n’ represents newline. But having them in your list can be a problem if you want to extract a given string from a list with no escape characters. This means, if you print the elements of the list, then the ‘\n’ characters will also be printed.

Example: Suppose you have two lists and you want to print the corresponding elements of each list simultaneously.

Expected Output:

Language – Developer
C – Dennis Ritchie
C++ – Bjarne Stroustrup
Python – Guido van Rossum
Java – James Gosling
R – John Chambers

Actual Output:

Language – Developer
C
– Dennis Ritchie
C++
– Bjarne Stroustrup
Python
– Guido van Rossum
Java
– James Gosling
R
– John Chambers

While printing the list lang, the newline character is also taken into account by Python. That leads to the corresponding item of the second list, i.e., dev to be printed on the new line instead of being printed alongside the item of list lang.

So, without further delay, let us dive into the solutions to visualize how you can remove the newline character from the list.

✨ Method 1: Using the replace() method

📌 replace() is an inbuilt method in Python that is used to replace an old substring with a new one.

Syntax:

string.replace(Old_value, New_value ,Count)

Here:

  • Old_value: Means the old or present substring
  • New_value: Means the new substring
  • Count: It is an optional parameter. It represents the number of substrings you want to replace. If left blank, the method replaces all the occurrence of the old substring with the new one.

📌 Thus, you can use the replace() method to replace all the ‘\n’  characters with the ‘ ’ whitespace character.

Solution

Output:

Language – Developer
C – Dennis Ritchie
C++ – Bjarne Stroustrup
Python – Guido van Rossum
Java – James Gosling
R – John Chambers

✨ Method 2: Using re.sub()

Another way to remove any newline characters from a list is to use regular expressions. You just need to import the re module (Regular Expressions module) and use the method sub() of this module.

📌 re.sub() method returns a string, replacing any substring which matches the pattern (provided) with a new substring in that string.

Syntax:

s = re.sub(‘pattern’, ‘replacement’, str)

Solution: Hence, using re.sub() you can easily remove single as well as consecutive occurrences of newline characters with empty strings as shown below.

Output:

Language – Developer
C – Dennis Ritchie
C++ – Bjarne Stroustrup
Python – Guido van Rossum
Java – James Gosling
R – John Chambers

✨ Method 3: Using strip()

📌 strip() is another built-in method in Python that removes specified characters from the beginning and end of a given string.

Syntax:

string.strip(characters)

Solution: You can use the strip('\n') method to remove the newline characters from the list elements as shown below.

Output:

Language – Developer
C – Dennis Ritchie
C++ – Bjarne Stroustrup
Python – Guido van Rossum
Java – James Gosling
R – John Chambers

✨ Method 4: Slice the List Elements

Slicing allows you to extract a substring from an entire string with the help of it’s index.

Example: The following code extracts all the characters from a string except the last character.

text = ‘ABCDE#’
print(text[:-1])
# OUTPUT: ABCDE

Thus, another work-around to our problem is to eliminate the newline characters is to slice the list elements and remove the ‘\n‘ character from the end of the string as shown below.

Output:

Language – Developer
C – Dennis Ritchie
C++ – Bjarne Stroustrup
Python – Guido van Rossum
Java – James Gosling
R – John Chambers

Explanation: We used i[:-1] and this ensured that the last character of the item is not included. Since the last character is ‘\n‘, hence we were able to eliminate it and print the proper output.

✨ Method 5: Using List Comprehension and Splitlines Function

Now, this is a tricky but effective way of eliminating ‘\n‘ characters from the list.

  • Use the splitlines() method to split the list element at line breaks i.e. “\n” and then store them in another list using a list comprehension.
  • But splitlines will store the items in another list. Therefore, you will now have a list of list. So, you have to flatten this list using another list comprehension and print the desired result.

Solution:

Output:

li: [[‘C’], [‘C++’], [‘Python’], [‘Java’], [‘R’]]
new_lang: [‘C’, ‘C++’, ‘Python’, ‘Java’, ‘R’]

Language – Developer
C – Dennis Ritchie
C++ – Bjarne Stroustrup
Python – Guido van Rossum
Java – James Gosling
R – John Chambers

✨ Method 6: Using str.maketrans(x,y) and str.translate(map)

  • Last but not least, we have str.maketrans() method. This method takes two substrings x and y of equal length and returns a translation table that maps each character in x to the character at the same position in y.
  • Thereafter, we need the str.translate() which returns a copy of the string where all characters have been mapped according to the dictionary returned by str.maketrans().

Solution

Output:

Language – Developer
C – Dennis Ritchie
C++ – Bjarne Stroustrup
Python – Guido van Rossum
Java – James Gosling
R – John Chambers

⚠️ Caution:

  • This might not be a suitable method in every scenario because we are replacing the newline character with a whitespace character in the above case while using the maketrans method.
  • Since, the presence of a whitespace does not hamper the final output in our code, hence this method deserves a mention in the list of our solutions.

Conclusion

Therefore, in this article, you learned about numerous methods to eliminate the newline character from a list element and I hope the above-mentioned concepts answered all your queries.

Read here: How To Print a Matrix in Python?

Please subscribe and stay tuned for more interesting tutorials in the future.

👨‍🎓 Author: Shubham Sayon
👨‍🎓
Co-Author: Anirban Chatterjee

Related Posts

  • How to comment out multiple lines in python
    16 October

    How to comment out multiple lines in python

    Table of ContentsMultiple Line Comments in PythonUsing the # characterUsing triple quotesUsing IDEs and Text Editors In this article, we will see about how to comment out multiple lines in python. The concept of comments is present in most programming languages. We use comments for documentation purposes. The compiler ignores them, but the user can […]

  • Get variable name as String in Python
    01 October

    How to get variable name as String in Python

    Table of ContentsWhat are variable names in Python?How to get a variable name as a string in Python?In Python 2.xIn Python 3.x In Python, there are several ways to convert a string to a variable name, but the reverse process is not exactly utilized so often in the programming world. This article focuses on how […]

  • Python print percent sign
    30 September

    Print percentage sign in python

    Table of ContentsIntroductionPrint the Percentage Sign in PythonUsing the %% characterUsing the format() functionUsing the f-string Introduction In this tutorial, we will see how to print percentage sign in python. The modulus operator (%) or the percentage sign has multiple usages in Python. We use this operator to calculate the remainder for the division between […]

  • Print blank line in Python
    23 September

    Print blank line in Python

    Table of ContentsWhat is a blank line in Python?Ways to print blank line in PythonUsing an empty print() functionUsing the print() function with newline characterUsing the print() function with an empty stringUsing the print() function with the sep parameterWays to print multiple blank lines in PythonUsing the print() function with multiple newline charactersUsing the print() […]

  • 17 September

    Write list to CSV in Python

    Table of ContentsUsing the write() function to write a list to a CSV fileUsing the csv module to write a list to a CSV fileUsing the numpy module to write a list to a CSV fileUsing the numpy.savetxt() function to write a list to a CSV fileUsing the numpy.tofile() function to write a list to […]

  • Python add commas to number
    11 September

    Python add commas to number

    Table of ContentsUsing the format() function to add commas to numbers in PythonUsing the fstrings to add commas to numbers in PythonUsing the regular expressions to add commas to numbers in PythonUsing the locale module to add commas to numbers in Python Python allows us to format values to get the final result in our […]

Leave a Reply

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

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.