473,387 Members | 1,573 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

remove the last character or the newline character?

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

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

Thank very much!
-Daniel

Sep 28 '06 #1
6 18370
Daniel Mark wrote:
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
Doing fileName[-1] lets you access the last character, but I'm not sure
about removing it since strings are immutable. It would still probably
be something like you did.
Question two:
Does python provide any function that can remove the newline character
from a string if it exists?
>>fileName = 'Perfect Setup.txt\n'
fileName.strip()
'Perfect Setup.txt'
>>>
Or you can use lstrip() or rstrip() to remove just the left or right side.
Sep 28 '06 #2
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
Sep 28 '06 #3
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


Sep 28 '06 #4
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'
fileName = fileName.rstrip('\n')
or just a plain:
fileName = fileName.strip()
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?
Not directly, since Python strings are immutable objects. If you want a
copy of the string without the last char *whatever it is*, you can just use
somestr = somestr[0:-1]

But in your situation, it's usually safer to use [lr]?strip()
>
Question two:
Does python provide any function that can remove the newline character
from a string if it exists?
Here again, you cannot *remove* anything from a string - you can just
have a modified copy copy of the string. (NB : answer is just above :
use str.strip())

HTH

--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Sep 28 '06 #5
"Daniel Mark" <da***********@gmail.comwrote:

In [2]: fileName = fileName[0:len(fileName)-1)] # remove the '\n'
To chop the last character regardless of what it is:

fileName = fileName[:-1]

You don't need the 0 since thats the default, and you can use a negative
index instead of subtracting from len(x).
Question two:
Does python provide any function that can remove the newline character
from a string if it exists?
To remove all trailing whitespace:

fileName = fileName.rstrip()

to just remove a newline:

fileName = fileName.rstrip('\n')
Sep 28 '06 #6
>Does python provide any function that can remove the newline character
>from a string if it exists?
>>fileName = 'Perfect Setup.txt\n'
>>fileName.strip()
'Perfect Setup.txt'
>>>

Or you can use lstrip() or rstrip() to remove just the left or right side.
Just a caveat with the non-qualified strip/rstrip/lstrip...it
will remove *all* whitespace, so if, for some reason, it's
significant, and you only want to remove newlines, you have to
specify it:
>>s = ' some text \t\n'
s.strip()
'some text'
>>s.rstrip()
' some text'
>>s.rstrip('\n')
' some text \t'

As the OP was talking about file-names, the use of
initial/terminal spaces is allowable (albeit imprudent),
depending on your platform, so one may or may not want to strip
them off.

Fortunately, as in many other areas, Python offers the
flexibility in an easy-to-use way, and comes with sensible defaults.

-tkc


Sep 28 '06 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: utab | last post by:
Hi there I am trying to read from a file, I am trying to read certain fields,there are 6 fields in this file like --------/--------/--------/--------/--------/--------/ All fields are 8...
13
by: comp.lang.php | last post by:
Other: <input name="school_type_other" size="30" maxlength="75" value="<?php if ($_POST) echo $_POST; else echo str_replace('"', '&quot;', str_replace('\\', '', $result->school_type_other)); ...
0
by: Adam Right | last post by:
Hi, I am using .net framework functions to send a mail over exchange server but i want to use newline character in the body. I cannot insert this character in the body. .NET constructs the...
5
by: Adam Right | last post by:
Hi, Is there a way to construct the mail body including newline characters by using .net framework mailing functions when sending an email? I cannot insert newline character into the body of the...
16
by: junky_fellow | last post by:
Is there any efficcient way of removing the newline character from the buffer read by fgets() ? Is there any library function that is similar to fgets() but also tells how many bytes it read...
1
by: toefraz | last post by:
Hello, all. I am writing a patch of code that displays the time and date in the middle of the line. I am using the asctime function from ctime but I don't want the trailing newline character after...
3
by: skris | last post by:
Hi All, I have some contents in a file named Msg.txt. I need to append the date right after the end of every line of that file. I tried out this code, but it did not work. >>> import datetime...
0
by: Gary Herron | last post by:
Support Desk wrote: The problem has nothing to do with lists. The readlines() function returns each line *with* its newline. To strip it off, use line.strip() Gary Herron
16
by: bgold12 | last post by:
Will newlines ever be standardized? I recently discovered that in a textarea, internet explorer adds \r\n for every newline you enter, while firefox adds \n. I know \r is also used in some...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.