remove the last character or the newline character?
Tim Chase
python.list at tim.thechases.com
Thu Sep 28 10:31:00 EDT 2006
> 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
You're close...
fileName = fileName[0:-1]
which is the same as
fileName = fileName[:-1]
which will lop off the last character. Much nicer than most
other languages I've used where you have to use the len() trick
you're using. Also, it's a common python idiom you'll see
frequently.
> Question two:
> Does python provide any function that can remove the newline character
> from a string if it exists?
In a discussion on this very matter a while back, I think the
final verdict was something like
fileName = fileName.rstrip('\n')
which will strip off *all* the trailing newlines. In most cases
(such as "for line in file('foo.txt'):" code), there's only one
to be stripped, so this works fine.
If you're ornary and want *only* the last '\n' lopped off, you'd
have to test for it:
if fileName[-1] == '\n': fileName = fileName[:-1]
There were caveats regarding "\n" vs. "\r\n" line endings, but if
the file comes in in ascii mode (rather than binary mode), Python
more or less smart enough to do the translation for you, leaving
the above code to work in the majority of cases.
-tkc
More information about the Python-list
mailing list