Need help using index on a string in python

Viewed 43

When I try to use indexing to get the last element of my line, it does not work( prints out a blank line). However, when I print the original line it works.

with open( newFile,"w") as f: 

    f.write("Model Number One" + "\n")
    for l in lines:
        if "ATOM" in l : 
            f.write(l[-1]) #Does NOT work, prints empty line
            f.write(l) # Prints the whole linem when I only want the last element of the line

When index is used When index is not used

3 Answers

The cause might be that the line has a new line character at the end. If the last element of the line is a "\n" since the file has multiple lines, then it will definitely print a blank line.

Each line is a string, and so each index is a single character, with the last one being a linebreak ('\n'). If you want to get whitespace-separated substrings out of that line, use strip to remove the linebreak, and split to split the resulting string on whitespace:

with open( newFile, "w") as f: 
    f.write("Model Number One" + "\n")
    for l in lines:
        elems = l.strip().split()
        if "ATOM" in elems: 
            f.write(elems[-1] + "\n")

As Kengru mentioned, there could be a newline at the end. To test try f.write(l[-2]) instead of f.write(l[-1]).

Related