为什么两个字符串的连接会产生类型错误?

时间:2015-07-20 00:34:18

标签: python

class node:
    def __init__(self, parent, daughters, edge):
        self.parent = parent
        self.daughters = daughters
        self.edge = edge
        trie.append(self)
        self.index = len(trie) - 1
        trie[parent].daughters.append(self.index)
    ...

    def SuffixTreeConstruction():
    global trie
    print(len(trie))
    for node in trie:
        if len(node.daughters) == 1:
            node.edge = ''.join([node.edge, trie[node.daughters[0]].edge])
            ...

我想取两个不同节点的边缘并将它们组合成一个字符串。边是字符串(for base in text: create node with base as edge)的迭代,所以我假设它们是单个字符串,而不是字符(带有数值)。但是,它们显然是整数。这有什么明显的原因吗?

Traceback (most recent call last):
  File "trieMatching.1.py", line 149, in <module>
    SuffixTreeConstruction()
  File "trieMatching.1.py", line 106, in SuffixTreeConstruction
    node.edge = ''.join([node.edge, trie[node.daughters[0]].edge])
TypeError: sequence item 1: expected str instance, int found

2 个答案:

答案 0 :(得分:1)

从错误中,node.edge或trie [node.daughters [0]]。edge]中的任何一个都可能是<type 'int'>类型 因此,尝试将它们转换为字符串,

node.edge = ''.join([str(node.edge), str(trie[node.daughters[0]].edge]))

答案 1 :(得分:0)

避免类型转换的另一种方法是使用onPause字符串来获得相同的结果&#34;

Realm

将为您完成类型转换。增加的好处是,您可以随意格式化事物......请参阅format docs and examples