Python字符串比较动作有趣
这很奇怪:Python字符串比较动作有趣,python,string,comparison,Python,String,Comparison,这很奇怪: 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, ch
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
1.f=f=真
1.f=f=真
仪表输出变量
我在互联网上搜索帮助,也许我的代码有问题。请帮忙。你不是在比较你认为你在比较的东西 您打印:
wordList[val+offset-1] != 'f'
但你实际上是在比较:
wordList[idx+offset-1] != 'f'
注意idx
和val
之间的区别
对于您的输入,第一个
val
是11
,而idx
是0
,因此您正在打印wordList[val+offset-1]
,它实际上是'f'
,因此等于空间中的值,但实际上您正在与wordList[idx+offset-1]
进行比较,后者是's'
<代码>'s'!='f'
确实是真的
这很奇怪。。。。什么奇怪?你还期待什么?在这个地方有什么好笑的?你在一个地方使用<代码> Val>代码>另一个地方,<代码> IDX < /代码>。样式NITPoice:考虑使用<代码> Wordsx和下划线< /COD>函数和实例名称。好的,这就是错误。谢谢网友们。Val是正确的变量。