首页 > 解决方案 > 需要帮助在 python 中的字符串上使用索引

问题描述

当我尝试使用索引来获取行的最后一个元素时,它不起作用(打印出一个空行)。但是,当我打印原始行时,它可以工作。

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

使用 索引时 不使用索引时

标签: pythonindexing

解决方案


原因可能是该行末尾有一个换行符。如果该行的最后一个元素是“\n”,因为文件有多行,那么它肯定会打印一个空行。


推荐阅读