- Python: Various methods to remove the newlines from a text file
- Method #1: Remove newlines from a file using replace()
- Syntax
- Example
- method #2: Remove newlines from a file using splitlines()
- Syntax
- Method #3: Remove newlines from a file using Regex
- Syntax
- Example
- Conclusion
- Related Tutorials:
- How to remove newlines from a string in Python 3?
- Strip newlines / line breaks from strings – Practical Example
- #1 – Using replace() method:
- #2 -Using strip() method:
- #3 -Using splitlines() method:
- Replace line breaks with space
- Removing newlines from a Python list
- Remove Line Breaks from a file
- Delete new lines python
- # Table of Contents
- # Remove newline characters from a List in Python
- # Remove all newlines from the original list, in place
- # Removing only the leading or trailing newline characters from a list
- # Remove newline characters from a List using str.replace()
- # Call strip() on each element of a List using a for loop
- # Additional Resources
Python: Various methods to remove the newlines from a text file
The ‘\n’ character represents the new line in python programming. However, this tutorial will show you various methods to remove the newlines from a text file.
Before starting, let us see the output of our file, which we want to remove all newlines from it.
Note: I’ve used the repr() function to print the file’s output with the ‘\n’ character.
Method #1: Remove newlines from a file using replace()
the replace() method replaces a specified phrase with another specified phrase. Therefore, we’ll use this method to replace the newline character with a non-value.
Syntax
Example
method #2: Remove newlines from a file using splitlines()
The splitlines() method splits a string at the newline break and returns the result as a list.
However, we will use the splitlines() to split the file’s output at ‘\n’ and the join() method to join the result.
Syntax
Method #3: Remove newlines from a file using Regex
We can also use the re.sub() function to remove the newlines from a text file.
Syntax
The sub() function works like replace() function.
Example
Conclusion
We’ve learned different methods to remove the newlines from a text file in this article. Moreover, if you want to remove the newlines from the beginning or end of the text file, you should use strip() and rstrip() methods.
Related Tutorials:
How to remove newlines from a string in Python 3?
To remove new line characters from a string in Python, use the replace() or the strip() functions. Here is an example of the code:
your_str = your_str.replace('/n', '') # alternatively your_str = your_str.strip()
Strip newlines / line breaks from strings – Practical Example
In this post, we will outline three methods that you can use to delete newlines from a string. We’ll discuss each technique and post example code for each case.
#1 – Using replace() method:
If you have a string that contains multiple line breaks, you can use the replace method and get multiple newlines removed / replaced.
mystring = 'This is my string \nThis comes in the next line.' print("With line breaks:" + mystring) print("After deleting line breaks:",mystring.replace('\n',''))
With line breaks:This is my string This comes in the next line. After deleting line breaks: This is my string This comes in the next line.
#2 -Using strip() method:
The Python strip() function removes any trailing character at the beginning and end of the string. So if your brealines are located before or after the string you can use strip() to get rid of them.
mystring = '\nThis is my string. \n' print("With newlines:" + mystring) print("After deleting the newlines:",mystring.strip())
With newlines: This is my string. After deleting the newlines: This is my string.
#3 -Using splitlines() method:
The splitlines() method helps to convert the lines into a split list. Hence, we can split our string into a list and then join it to form a string value.
mystring = 'This is my string \nThis comes in the next line.' print("With line breaks:" + mystring) print("After deleting new lines:",''.join(mystring.splitlines()))
With line breaks:This is my string This comes in the next line. After deleting new lines: This is my string This comes in the next line.
Replace line breaks with space
Another common case is to place empty spaces instead of newlines in a string. Let’s look at a simple example:
my_str = 'This is a string that\ni read from a file\n' print(my_str)
This will return the following:
This is a string that i read from a file
Let’s replace the line breaks with a space and print the result:
This is a string that i read from a file
Removing newlines from a Python list
In a similar fashion you can easily strip newlines off a list of strings.
Let’s assume you have the following list:
orig_lst = ['Python', 'R', 'GO\n', 'Haskell']
We can easily strip the newlines off the list elements with a list comprehension and the rstrip() function:
new_lst = [x.rstrip() for x in orig_lst] print(new_lst)
Alternatively we can obtain the same result by using the replace() function:
new_lst = [x.replace('\n','') for x in orig_lst]
We can also replace the newline characters with a space:
new_lst = [x.replace('\n',' ') for x in orig_lst]
Remove Line Breaks from a file
Last topic for this tutorial is removing newlines from the contents of a text file.
We know how to read text files into a Python list using readlines(). In this case, we need a somewhat different approach. We first want to read contents of the text file into a string. This is easily accomplished by the file object read() function. We can then manipulate the string as needed, in this case replacing the newline characters with a space.
with open (file_path, 'r') as f: print(f.read().replace('\n',' '))
Delete new lines python
Last updated: Dec 20, 2022
Reading time · 5 min
# Table of Contents
# Remove newline characters from a List in Python
To remove the newline characters from a list:
- Use a list comprehension to iterate over the list.
- Use the str.strip() method to remove the leading and trailing newlines from each string.
- The new list won’t contain leading and trailing newlines.
Copied!my_list = ['bobby\n', 'hadz\r\n', '\ncom\r\n'] # ✅ Remove leading and trailing newline characters from list new_list = [item.strip() for item in my_list] print(new_list) # 👉️ ['bobby', 'hadz', 'com'] # --------------------------------------------- # ✅ Remove ALL newline characters from list new_list = [ item.replace('\r', '').replace('\n', '') for item in my_list ] print(new_list) # 👉️ ['bobby', 'hadz', 'com']
If you need to remove the newline characters from a string, use the following code sample instead.
Copied!my_str = '\r\nfirst row\r\n' print(repr(my_str)) # 👉️ 'first row\r\n' # ✅ remove leading and trailing carriage returns result_1 = my_str.strip() print(repr(result_1)) # 👉️ 'first row' # --------------------------------------------- # ✅ remove only trailing carriage returns result_2 = my_str.rstrip() print(repr(result_2)) # 👉️ '\r\nfirst row' # --------------------------------------------- # ✅ remove all carriage returns from string result_3 = my_str.replace('\r', '').replace('\n', '') print(repr(result_3)) # 👉️ 'first row'
The examples use a list comprehension to iterate over the list.
List comprehensions are used to perform some operation for every element or select a subset of elements that meet a condition.
On each iteration, we use the str.strip() method to remove the leading and trailing newlines from each string.
Copied!my_list = ['bobby\n', 'hadz\r\n', '\ncom\r\n'] new_list = [item.strip() for item in my_list] print(new_list) # 👉️ ['bobby', 'hadz', 'com']
The str.strip method returns a copy of the string with the leading and trailing whitespace removed.
The strings in the new list won’t contain any leading and trailing newline characters.
The list comprehension doesn’t mutate the original list, it returns a new list.
# Remove all newlines from the original list, in place
If you need to mutate the original list, use a slice.
Copied!my_list = ['bobby\n', 'hadz\r\n', '\ncom\r\n'] my_list[:] = [item.strip() for item in my_list] print(my_list) # 👉️ ['bobby', 'hadz', 'com']
We used the my_list[:] syntax to get a slice that represents the entire list, so we can assign to the variable directly.
The slice my_list[:] represents the entire list, so when we use it on the left-hand side, we are assigning to the entire list.
This approach changes the contents of the original list.
# Removing only the leading or trailing newline characters from a list
If you only need to remove the leading or trailing newline characters from each string in a list, use the str.lstrip() or str.rstrip() methods.
Copied!my_list = ['bobby\n', 'hadz\r\n', '\ncom\r\n'] new_list = [item.rstrip() for item in my_list] print(new_list) # 👉️ ['bobby', 'hadz', '\ncom'] new_list = [item.lstrip() for item in my_list] print(new_list) # 👉️ ['bobby\n', 'hadz\r\n', 'com\r\n']
The str.rstrip method returns a copy of the string with the trailing whitespace removed.
The str.lstrip method returns a copy of the string with the leading whitespace removed.
Alternatively, you can use the str.replace() method.
# Remove newline characters from a List using str.replace()
This is a three-step process:
- Use a list comprehension to iterate over the list.
- Use the str.replace() method to remove all newline characters from each string.
- The items in the new list won’t contain any newline characters.
Copied!my_list = ['bobby\n', 'hadz\r\n', '\ncom\r\n'] new_list = [item.replace('\r', '').replace('\n', '') for item in my_list] print(new_list) # 👉️ ['bobby', 'hadz', 'com']
We used the str.replace() method to remove the newline characters from each string in the list.
This approach removes all newline characters from each string in the list. Not just the leading and trailing ones.
The str.replace method returns a copy of the string with all occurrences of a substring replaced by the provided replacement.
The method takes the following parameters:
Name | Description |
---|---|
old | The substring we want to replace in the string |
new | The replacement for each occurrence of old |
count | Only the first count occurrences are replaced (optional) |
We provided an empty string as the replacement because we want to remove all newline characters.
Notice that we called the str.replace() method 2 times.
This is necessary because the newline characters differ between operating systems.
Windows uses \r\n as an end of line character, whereas \n is the default in Unix.
# Call strip() on each element of a List using a for loop
This is a three-step process:
- Use a for loop to iterate over the list.
- Call the str.strip() method on each list element.
- Use the list.append() method to append the result to a new list.
Copied!a_list = [' bobby\n ', ' hadz\n ', ' com\n '] new_list = [] for item in a_list: new_list.append(item.strip()) print(new_list) # 👉️ ['bobby', 'hadz', 'com']
We used a for loop to iterate over the list.
On each iteration, we call the str.strip() method on the current list item and append the result to a new list.
The list.append() method adds an item to the end of the list.
If you need to mutate the original list instead of creating a new list, use the enumerate() function.
Copied!a_list = [' bobby\n ', ' hadz\n ', ' com\n '] for index, item in enumerate(a_list): a_list[index] = item.strip() print(a_list) # 👉️ ['bobby', 'hadz', 'com']
The enumerate function takes an iterable and returns an enumerate object containing tuples where the first element is the index and the second is the corresponding item.
Copied!my_list = ['bobby', 'hadz', 'com'] for index, item in enumerate(my_list): print(index, item) # 👉️ 0 bobby, 1 hadz, 2 com
On each iteration, we reassign the item at the current index to the result of calling the str.strip() method on it.
Which approach you pick is a matter of personal preference. I’d use a list comprehension because I find them quite direct and easy to read.
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.