Home » Python

Remove trailing new line in Python

Example of strip(), lstrip() and rstrip() methods: Here, we are going to learn how to remove trailing new line in Python programming language?
Submitted by Sapna Deraje Radhakrishna, on November 23, 2019

Python supports inbuilt methods called strip(), lstrip() and rstrip() which works on string variable and removes the trailing newline or spaces as per given argument.

1) strip()

The strip() method remove characters from both left and right based on the argument. It returns a copy of the string with both leading and trailing characters stripped.

When the combination of characters in the chars argument mismatches the character of the string in the left/right, the method stops removing the leading/trailing characters respectively,

Syntax:

    string.strip([chars])

Here, the chars are an optional argument. If not provided, all the leading and trailing whitespaces shall be removed.

Example for strip()

>>> test_string = "   include help is learning source  "
>>> print(test_string.strip())
include help is learning source
>>> print(test_string.strip('   include'))
help is learning sour #here along with leading space and the word 'include', the char 'e' will be removed from the trailing
>>> print(test_string.strip('   test'))
include help is learning sourc
>>> test_str = "simple string"
>>> print(test_str.strip('s'))
imple string

2) lstrip()

The lstrip() method returns a copy of the string with leading characters removed based on the argument passed. Similar to strip(), all the combinations of characters in the argument are removed from the left of the string, until the first mismatch.

Syntax:

    string.lstrip([chars])

chars are an optional argument which if not provided, removes all leading whitespaces from the string.

Example of usage of lstrip()

>>> test_string = '   test string'
>>> print(test_string.lstrip())
test string
>>> print(test_string.lstrip('test'))
   test string
>>> print(test_string.lstrip('    test'))#here along with leading space the chars 'st' from 'string' is also removed
ring

3) rstrip()

The rstrip() method returns a copy of the string with trailing spaces removed based on the arguments passed. Here trailing is the right based argument. Similar to strip() and lstrip(), all the combinations of characters in the chars argument are removed from the right of the string until the first mismatch.

Syntax:

    string.rstrip([chars])

Here, the chars are optional argument, which if not provided all the whitespaces are removed from the string.

Example usage of rstrip()

>>> test_string = 'sample test string    '
>>> print(test_string.rstrip())
sample test string
>>> test_string = 'sample test string    test\n'
>>> print(test_string)
sample test string    test

>>> print(test_string.rstrip('\n'))
sample test string    test
>>>


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.