Remove Newline characters from a List or a String in Python

avatar
Borislav Hadzhiev

Last updated: Dec 20, 2022
5 min

banner

# Table of Contents

  1. Remove newline characters from a List in Python
  2. Remove all newlines from the original list, in place
  3. Removing only the leading or trailing newline characters from a list
  4. Remove newline characters from a List using str.replace()
  5. Call strip() on each element of a List using a for loop

# Remove newline characters from a List in Python

To remove the newline characters from a list:

  1. Use a list comprehension to iterate over the list.
  2. Use the str.strip() method to remove the leading and trailing newlines from each string.
  3. The new list won't contain leading and trailing newlines.
main.py
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']

remove newline characters from list

If you need to remove the newline characters from a string, use the following code sample instead.

main.py
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.

main.py
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.

main.py
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']

remove all newlines from original list in place

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.

main.py
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']

remove only leading or trailing newline characters from list

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:

  1. Use a list comprehension to iterate over the list.
  2. Use the str.replace() method to remove all newline characters from each string.
  3. The items in the new list won't contain any newline characters.
main.py
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']

remove newline characters from list using str replace

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:

NameDescription
oldThe substring we want to replace in the string
newThe replacement for each occurrence of old
countOnly 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:

  1. Use a for loop to iterate over the list.
  2. Call the str.strip() method on each list element.
  3. Use the list.append() method to append the result to a new list.
main.py
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']

call strip on each element of list using for loop

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.

main.py
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.

main.py
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.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev