【问题标题】:Python: Search for a string with special charactersPython:搜索带有特殊字符的字符串
【发布时间】:2012-03-14 15:51:58
【问题描述】:
在我的python代码中:
_response = '"hidden" name="transactionA**rr**ay" value="[{"id":519292,"status":0,"parentid":"'
_responseVal = 'transactionA**r**ay" value="[{"id":'
_breakStr = ','
startIndex = _response.find(_responseVal) + len(_responseVal)
remString = _response[startIndex:]
print 'Remaining string: '+remString
我期待一个空字符串,因为我的搜索字符不存在,而是我得到
剩余字符串:
【问题讨论】:
标签:
python
search
special-characters
substring
【解决方案1】:
您似乎想从较大的字符串中删除给定的字符串。您的具体问题是 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)
【解决方案2】:
浓缩成精髓,问题是这样的:
>>> s = "abcde"
>>> s.find("X")
-1
问题是字符串的find 方法在失败时返回-1,所以startIndex 原来是在_response 字符串的中间某处。可以测试_response.find返回的值是否为-1,并进行特殊处理。更简单的是切换到使用_response.index,这会引发ValueError;然后,您可以捕获异常并适当地处理它。
【解决方案3】:
find() 在找不到匹配项时返回 -1,然后添加 len(_responseVal),startIndex 指向 _response 中间的某个位置。为什么你会期望一个空字符串?