Python strip with n

Python strip with n

You should be able to use line.strip(n) and line.strip(t). But these dont modify the line variable…they just return the string with the n and t stripped. So youll have to do something like

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

That should work for removing from the start and end. If you have n and t in the middle of the string, you need to do

line = line.replace(n,)
line = line.replace(t,)

to replace the n and t with nothingness.

The strip() method removes whitespace by default, so there is no need to call it with parameters like t or n. However, strings in Python are immutable and cant be modified, i.e. the line.strip() call will not change the line object. The result is a new string which is returned by the call.

As already mentioned, it would help if you posted an example from your input file. If there are more than one number on each line, strip() is not the function to use. Instead you should use split(), which is also a string method.

To conclude, assuming that each line contains several floats separated by whitespace, and that you want to build a list of all the numbers, you can try the following:

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

Python strip with n

You can use:

mylist = []
# Assuming that you have loaded data into a lines variable. 
for line in lines:

to get a python list with only the field values for all the lines of data.

Leave a Reply

Your email address will not be published. Required fields are marked *