• Register
0 votes
115 views

Problem:

What is the Python equivalent of Perl's chomp function, which removes the last character of a string if it is a newline?

 

200 points

Please log in or register to answer this question.

1 Answer

0 votes

 

Solution:

The strip() technique evacuates whitespace as a matter of course, so there is no compelling reason to call it with parameters like '\t' or '\n'. In any case, strings in Python are unchanging and can't be altered, for example the line. strip() call won't change the line object. The outcome is another string which is returned by the call. 

As of now referenced, it might be ideal on the off chance that you posted a model from your information document. In the event that there are more than one number on each line, strip() isn't the capacity to utilize. Rather you should utilize split(), which is likewise a string technique. 

To finish up, accepting that each line contains a few buoys isolated by whitespace, and that you need to fabricate a rundown of the considerable number of numbers, you can attempt the accompanying:

floats = []
with open(filename) as f:
    for line in f:
        floats.extend([float(number) for number in line.split()])

 

Another solution:

You ought to have the option to utilize line.strip('\n') and line.strip('\t'). In any case, these don't adjust the line variable...they simply return the string with the \n and \t stripped. So you'll need to accomplish something like

line = line.strip('\n')
line = line.strip('\t')

That should work for expelling from the beginning and end. On the off chance that you have \n and \t in the string, you have to do

line = line.replace('\n','')
line = line.replace('\t','')
460 points