Python 字符串连接/索引给定索引器

Python 字符串连接/索引给定索引器,python,Python,我正在尝试一些相对基本的字符串连接,但似乎找不到我收到的错误的来源 我的代码如下: def crossover(dna1, dna2): """ Slices both dna1 and dna2 into two parts at a random index within their length and merges them. """ pos = int(random.random()*DNA_SIZE) return (dna1[:pos

我正在尝试一些相对基本的字符串连接,但似乎找不到我收到的错误的来源

我的代码如下:

def crossover(dna1, dna2):
    """
    Slices both dna1 and dna2 into two parts at a random index within their
    length and merges them.
    """
    pos = int(random.random()*DNA_SIZE)
    return (dna1[:pos]+dna2[pos:], dna2[:pos]+dna1[pos:])
稍后,我以以下方式引用此函数,其中变量
ind1Aff
ind2Aff
先前已定义为二进制字符串

ind1Aff, ind2Aff = crossover(ind1Aff, ind2Aff)
    return (dna1[:pos]+dna2[pos:], dna2[:pos]+dna1[pos:])
IndexError: invalid index to scalar variable.
但是,在运行代码时,会出现以下错误:

ind1Aff, ind2Aff = crossover(ind1Aff, ind2Aff)
    return (dna1[:pos]+dna2[pos:], dna2[:pos]+dna1[pos:])
IndexError: invalid index to scalar variable.
我尝试将其稍微更改为
dna1[0:pos]+dna2[pos:DNA\u SIZE]
(其中DNA\u SIZE是字符串的长度)等,但没有成功。也有类似的消息来源,但它们似乎没有帮助


我做错了什么?

如评论中所述,最有可能的问题是您实际上没有传入字符串。在对字符串执行拆分之前,请尝试打印类型(即类型(dna1))

当您传递一个普通python字符串时,您的代码按预期工作:

import random


def crossover(dna1, dna2):
    """ 
    Slices both dna1 and dna2 into two parts at a random index within their
    length and merges them.
    """
    DNA_SIZE = len(dna1)
    pos = int(random.random()*DNA_SIZE)
    return (dna1[:pos]+dna2[pos:], dna2[:pos]+dna1[pos:])


def main():
    one = '000000000000000'
    two = '111111111111111'
    ind1Aff, ind2Aff = crossover(one, two)
    print ind1Aff
    print ind2Aff


if __name__ == "__main__":
    main()
输出:

000011111111111
111100000000000

您还可以在应用字符串拆分之前插入str(dna1)和str(dna2)

。。。你确定那些是弦吗?我以前在使用内置类型时从未见过这种错误。请尝试使用
dna1
dna2
的一些示例值。它们当然不是字符串。您要传递什么值来代替ind1Aff和ind2Aff?使用的值是二进制字符串,因此其中一个值类似于
10100011001000
。您能检查二进制字符串的
类型吗?您确定它是字符串而不是其他自定义数据结构吗?