Custom Search

Saturday, December 11, 2010

python django remove trailing newline from string

python django remove trailing newline from string

fileName = "some text\n"

fileName = fileName.rstrip("\n")
This will remove more than one newline if present.

If you only want to remove one newline, use

if fileName[-1:] == '\n':
fileName = fileName[:-1]

fileName[:-1] is all of the string except for its last character, which is useful for
removing the trailing newline from a string.

* because list exclude the last element.

fileName[-1:] ------> get last element.
fileName[:-1] -------? get all elements except last one.

-------------------------------------------------

>>> s = ' some text \t\n'
>>> s.strip()

'some text'
>>> s.rstrip()

' some text'
>>> s.rstrip('\n')

' some text \t'

No comments:

Post a Comment