Home >Backend Development >Python Tutorial >How Can I Remove Trailing Newlines from a String in Python?

How Can I Remove Trailing Newlines from a String in Python?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-15 17:44:10411browse

How Can I Remove Trailing Newlines from a String in Python?

Removing Trailing Newlines with Python

To remove the trailing newline character from a string in Python, employ the rstrip() method.

Python's rstrip() conveniently removes trailing whitespace, including newlines.

>>> 'test string\n'.rstrip()
'test string'

If you specifically want to remove only newlines, specify it using the following syntax:

>>> 'test string \n \r\n\n\r \n\n'.rstrip('\n')
'test string \n \r\n\n\r '

In addition to rstrip(), Python provides the analogous methods strip() and lstrip(). These methods offer finer control over whitespace removal:

  • strip(): Removes both leading and trailing whitespace from a string.
  • lstrip(): Removes only leading whitespace.
  • rstrip(): Removes only trailing whitespace.

An example showcasing their usage:

>>> s = "   \n\r\n  \n  abc   def \n\r\n  \n  "
>>> s.strip()
'abc   def'
>>> s.lstrip()
'abc   def \n\r\n  \n  '
>>> s.rstrip()
'   \n\r\n  \n  abc   def'

The above is the detailed content of How Can I Remove Trailing Newlines from a String in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn