Remove carriage return from a String in Python

avatar

Borislav Hadzhiev

Last updated: Aug 13, 2022

banner

Photo from Unsplash

Remove carriage return from a String in Python #

Use the str.strip() method to remove the carriage returns from a string, e.g. result = my_str.strip(). The str.strip() method will return a new string with all the leading and trailing carriage returns removed.

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 training 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'
We used the str.strip() method to remove the leading and trailing carriage returns from a string.

The str.strip method returns a copy of the string with the leading and trailing whitespace removed.

The method does not change the original string, it returns a new string. Strings are immutable in Python.

If you only need to remove the trailing carriage returns from the string, use the str.rstrip()method.

main.py
my_str = '\r\nfirst row\r\n' result_2 = my_str.rstrip() print(repr(result_2)) # 👉️ '\r\nfirst row'

The str.rstrip method returns a copy of the string with the trailing whitespace removed.

If you need to remove all carriage returns from the string, use the str.replace() method.

To remove all the carriage returns from a string:

  1. Use the str.replace() method to remove all occurrences of \r characters from the string.
  2. Use the str.replace() method to remove all occurrences of \n characters from the string.
  3. The new string will not contain any carriage returns.
main.py
my_str = '\r\nfirst row\r\n' result = my_str.replace('\r', '').replace('\n', '') print(repr(result)) # 👉️ 'first row'

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 carriage returns.

Notice that we called the str.replace() method 2 times.

This is necessary because the carriage return characters differ between operating systems.

Windows uses \r\n as an end of line character, whereas \n is the default in Unix.

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.