的Python:搜索包含特殊字符

问题描述:

在我的Python代码的字符串:的Python:搜索包含特殊字符

_response = '"hidden" name="transactionA**rr**ay" value="[{"id":519292,"status":0,"parentid":&quot' 
_responseVal = 'transactionA**r**ay" value="[{"id":' 
_breakStr = ',' 
startIndex = _response.find(_responseVal) + len(_responseVal) 
remString = _response[startIndex:] 
print 'Remaining string: '+remString 

我期待一个空字符串,因为我的搜索字符不存在,相反,我得到 剩余的字符串:

+0

请正确编辑您的代码,这是不可能的 – Petrucio 2012-02-24 06:56:51

+0

问题是什么?请阅读[常见问题]和[问] – 2012-02-24 07:29:08

find()在找不到匹配项时返回-1,然后添加len(_responseVal),startIndex指向_response中间的某处。为什么你会期望一个空字符串?

+0

好的和简洁的答案。 – 2012-02-24 07:41:11

下冷凝为要领,麻烦的是这样的:

>>> s = "abcde" 
>>> s.find("X") 
-1 

的问题是,一个字符串的find方法返回-1失败,所以startIndex原来是在_response的中间位置串。您可以测试从_response.find返回的值,看它是否为-1并专门处理它。更简单的是切换到使用_response.index,这会产生ValueError;那么你可以抓住异常并适当地处理它。

看来你想从一个较大的字符串中删除给定的字符串。你的具体问题是find返回-1,并且这个值没有被检查,并且你需要将len(_responseVal)添加到底部的行,而不是顶部改变开始索引的行。就像这样:

remString = '' 
startIndex = _response.find(_responseVal) 
if startIndex != -1: 
    endIndex = startIndex + len(_responseVal) 
    remString = _response[startIndex : endIndex] 

但更容易完成同样的事情的方法就是简单地使用替代:

remString = _response.replace(_responseVal, '') 

如果你想如果responseVal没有响应包含它是空的,因为您似乎:

remString = '' 
if _response.find(_responseVal) != -1: 
    remString = _response.replace(_responseVal)