2024-04-25 02:04:22 发布
网友
以下是我的一些代码:
with open ('sampleID.txt', 'r') as inF: for line in inF: if 'Sample ID:' in line: SID = line.split(':')[1]
文本文件(sampleID.txt文件)包含以下内容: 样品编号:110715516102 ABC
现在的问题是,如何更正代码,使SID=110715516102 这个行。拆分是工作,但它包括一个空白,我想避免这个。你知道吗
非常感谢你的帮助/支持
我相信您所需要做的就是通过strip()函数运行最后一个字符串。你知道吗
strip()
str.strip([chars])Return a copy of the string with the leading and trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace.
str.strip([chars])
Return a copy of the string with the leading and trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace.
因此,循环中的命令如下所示:
SID = line.split( ":" )[ 1 ].strip()
参考文献:
可以使用strip()函数删除额外的空格:
with open ('sampleID.txt', 'r') as inF: for line in inF: if 'Sample ID:' in line: SID = line.split(':')[1].strip()
如果行布局总是相同的(即ID前面的空格数相同),只需执行以下操作:
SID = line.split()[2]
我相信您所需要做的就是通过
strip()
函数运行最后一个字符串。你知道吗因此,循环中的命令如下所示:
参考文献:
可以使用
strip()
函数删除额外的空格:如果行布局总是相同的(即ID前面的空格数相同),只需执行以下操作:
相关问题 更多 >
编程相关推荐