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

  • Convert String to Boolean in Python
    20 June

    Convert String to Boolean in Python

    Table of ContentsUsing the bool() method to convert string to Boolean in Python.Using the distutils.util.strtobool() method to convert a string to Boolean in Python.Using list comprehension to convert a string to Boolean in Python.Using the map() function along with Lambda function to convert a string to Boolean in Python.Using the JSON parser to convert a […]

  • Convert float to int in Python
    19 June

    Convert float to int in Python

    Table of ContentsUsing the int() function to convert float to int in PythonUsing the math module functions to convert float to int in PythonUsing ceil()Using trunc()Using floor Python provides several in-built functions and modules for datatype conversions. Floating-point numbers can be easily converted to integers using some of these in-built functions. This tutorial will discuss […]

  • Detect keypress in Python
    12 June

    Detect keypress in Python

    Table of ContentsUsing the keyboard module to detect keypress in PythonUsing the pynput module to detect keypress in PythonUsing the msvcrt module to detect keypress in Python Python allows us to work with user input in its programs. We can also work with hardware devices in Python. In this article, we will discuss how to […]

  • Copy a dictionary in Python
    12 June

    7 ways to copy a dictionary in python

    Table of ContentsUsing the copy() function to copy a dictionary in PythonUsing the deepcopy() function to copy a dictionary in PythonUsing the dict() function to copy a dictionary in PythonUsing the unpack operator ** to copy a dictionary in PythonUsing the update() function to copy a dictionary in PythonUsing the dictionary comprehension method to copy […]

  • Escape quotes in Python
    11 June

    Escape quotes in Python

    Table of ContentsUsing \ to escape quotes in PythonUsing \ with replace() to escape quotes in PythonUsing json.dumps to escape quotes in PythonUsing triple single or double quotes to escape quotes in pythonUse r to include \ and quotes in String 💡 Outline You can use \ to escape quotes in Python. If you want […]

  • Sleep for milliseconds in python
    31 May

    How to sleep for milliseconds(ms) in Python

    Table of ContentsUse time.sleep() function to make the program sleep for millisecondsUse threading.Timer() function to make the program sleep for milliseconds 💡 Outline You can use time.sleep() method to sleep for milliseconds in Python. If you want to delay python program by 500 ms, then you need to pass 0.5 as parameter to sleep method. […]

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.