Re: remove the last character or the newline character?



Daniel Mark wrote:
Hello all:

I have the following snippet:

In [1]: fileName = 'Perfect Setup.txt\n'
In [2]: fileName = fileName[0:len(fileName)-1)] # remove the '\n'
character
In [3]: fileName
Out[3]: 'Perfect Setup.txt'

Question one:
Does python provide any function that can remove the last character of
a string?
I don't know whether or not the method I used is efficient

fileName = fileName[:-1]

Question two:
Does python provide any function that can remove the newline character
from a string if it exists?

fileName = fileName.rstrip("\n")

though 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]

Georg
.



Relevant Pages

  • chapter3
    ... An Informal Introduction to Python ... the hash character, "#", and extend to the end of the physical line. ... string literal is just a hash character. ... Unicode Strings ...
    (Ubuntu)
  • Re: UTF-8 / German, Scandinavian letters - is it really this difficult?? Linux & Windows XP
    ... > If I have this in the beginning of my Python script in Linux: ... > in strings and in Tk GUI button labels and GUI window titles and in ... effect on byte string literals. ... DIAERESIS can be encoded in many different character sets, ...
    (comp.lang.python)
  • Re: Input statement question
    ... I'm still new at Python and have been away from programming for a ... but it's not going to go away until Python 3.0. ... > until the specified ending character is received. ... > always be a string. ...
    (comp.lang.python)
  • Re: Problem with sets and Unicode strings
    ... So this is a bug in Python? ... > statement directly compares a unicode string with a byte string. ... If you put character U+00E4 into a unicode string python ... the ASCII codec, because my file is encoded with UTF-8. ...
    (comp.lang.python)
  • Re: Unexpected regex Behavior
    ... wish to do special processing if any chunk ends with the carriage-return ... the "^" character is guaranteed to match only the beginning ... the "$" character only the end (or before the newline at ... the string contains only one line. ...
    (comp.lang.perl.misc)