Python 字符串比较搞笑

Python string comparison acting funny

这很奇怪:

def separatewordsbycaps(word):
    """This custom template will add space to fields when it finds a capital letter.
    Ex. InstrumentDeployment --> Instrument Deployment"""

    wordList = list(word)

    spaceIndexes = [index for index, char in enumerate(wordList) if char.isupper() and index!=0]
    offset = 0
    space = "f"
    for idx, val in enumerate(spaceIndexes):
        print "1."+wordList[val+offset-1]+"!=" + space +"= " + str(wordList[idx+offset-1] != space)
        print type(wordList[val+offset-1])
        print type(space)
        if wordList[idx+offset-1] != space:
            wordList.insert(val+offset, space)
            offset += 1

    return ''.join(wordList)

print separatewordsbycaps("InstrumentfOutputfVariables")

输出:

1.f!=f= True
<type 'str'>
<type 'str'>
1.f!=f= True
<type 'str'>
<type 'str'>
InstrumentffOutputffVariables

我在网上搜索帮助,也许我的代码有问题。请帮忙。

你不是在比较你认为你在比较的东西。

你打印:

wordList[val+offset-1] != 'f'

但你实际上是在比较:

wordList[idx+offset-1] != 'f'

注意 idxval 之间的区别。

对于您的输入,第一个 val11idx0,所以您打印的 wordList[val+offset-1] 实际上是 'f',因此等于 space 中的值,但您实际上是在与 wordList[idx+offset-1] 进行比较,即 's''s' != 'f' 确实是 True.