python - 需要帮助在 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
解决方案
原因可能是该行末尾有一个换行符。如果该行的最后一个元素是“\n”,因为文件有多行,那么它肯定会打印一个空行。
推荐阅读
- c# - 使用 DefaultRequestHeaders 发送请求两次?
- git - git merge 命令以 1 退出,如果它已经是最新的
- azure - PowerShell Azure 存储模拟器
- android - Android 应用程序是否可以忽略所有物理用户输入?
- android - ImageButton 自动旋转选中的图片
- ios - 如何在容器视图中显示 WKWebView 内容
- c# - 使用 .NET Core 和 Angular 6 启用 CORS
- protocol-buffers - 解码 protobuf 二进制文件——得到“无法解析输入”
- maven - 在 Maven (pom.xml) 和 Gradle (build.gradle) 之间共享依赖版本
- ssis - 由于 ODBC 数据流任务错误,SSIS 包在 VS 中有效,但在 SSIS 中无效