在 insert() 中调用变量

Calling variable inside insert()

我有两个文本文件,我正尝试在 python 2.7.7 中使用它们,其结构如下例所示:

sequence_file.txt:

MKRPGGAGGGGGSPSLVTMANSSDDGYGGVGMEAEGDVEEEMMACGGGGE

positions.txt

10
7
4

我想做的是在positions.txt:

中指示的每个位置的序列中插入一个#符号
MKR#PGG#AGGG#GGSPSLVTMANSSDDGYGGVGMEAEGDVEEEMMACGGGGE

目前我的代码如下:

# Open sequence file, remove newlines:
with open ("sequence_file.txt", "r") as seqfile:
    seqstring=seqfile.read().replace('\n', '').replace('\r', '')

# Turn sequence into list
seqlist = list(sequence)

# Open positions.txt, and use each line as a parameter for the insert() function.
with open("positions.txt") as positions:
    for line in positions:
        insertpoint = line.rstrip('\n')
        seqlist.insert(insertpoint, '#')

seqlist = list(sequence)

该代码的最后一块是它失败的地方。我试图让它读取第一行,trim 换行符 (\n),然后将该行用作 insert() 命令中的变量(插入点)。但是,每当我尝试这个时,它都会告诉我:

Traceback (most recent call last):
File "<pyshell#8>", line 4, in <module>
seqlist.insert(insertpoint, '#')
TypeError: an integer is required

如果我测试它并尝试 'print insertpoint' 它会正确生成数字,所以我对错误的解释是当我使用 insert() 命令时它正在读取 'insertpoint' 作为文本而不是刚刚设置的变量。

任何人都可以提出这可能出了什么问题吗?

发生的情况是 str.rstrip() returns 一个 字符串 ,但 insert() 需要一个整数。

解决方法:将该字符串转换为整数:

insertpoint = int(line.rstrip('\n'))

注意: 当您打印 insertpoint 时,它显示时没有 '' 但它是一个字符串。您可以通过打印其类型来检查它:

print(type(insertpoint)) # <type 'str'>

看来您可能需要将 int() 放在插入点周围:

seqlist.insert(int(insertpoint), '#')