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
Release: 2024-12-15 17:44:10
Original
409 people have browsed it

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'
Copy after login

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 '
Copy after login

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'
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template