某处我是一个白痴,但我找不到在哪里。Python:相同的字符串切片,两个不同的结果
我正在通过ODBC使用PostgreSQL数据库运行Python脚本。我试图从数据库异常消息中提取有意义的内容。这里是原始消息,为了可读性而添加了换行符:
(-2147352567, 'Exception occurred.', (0, 'Microsoft OLE DB Provider for ODBC Drivers',
'ERROR: Charge not in a correct status to delete;\nError while executing the query',
None, 0, -2147467259), None)
请注意,此字符串中有两组括号。首先,我找到外侧的位置并将其切断。这给了预期的结果:
-2147352567, 'Exception occurred.', (0, 'Microsoft OLE DB Provider for ODBC Drivers',
'ERROR: Charge not in a correct status to delete;\nError while executing the query',
None, 0, -2147467259), None
然后,用尽可能我可以告诉相同的代码,我脱光了另一组括号,一切他们之外。这给出了这样的结果:
(0, 'Microsoft OLE DB Provider for ODBC Drivers',
'ERROR: Charge not in a correct status to delete;\nError while executing the query',
None, 0, -214746725
左括号仍然在这里,即使我使用find()方法以同样的方式的结果,将一个开放的括号位置作为片的起点,两次。
下面是代码:
print (errorString)
openParenLocation = errorString.find('(')
closeParenLocation = errorString.rfind(')')
strippedString = errorString[openParenLocation + 1:closeParenLocation]
openParenLocation = strippedString.find('(')
closeParenLocation = strippedString.rfind(')')
dbErrorString = errorString[openParenLocation + 1:closeParenLocation]
print (strippedString)
print ("{}, {}".format(openParenLocation, closeParenLocation))
print (dbErrorString)
这里是原始输出,不添加换行符:使用更小的字符串
(-2147352567, 'Exception occurred.', (0, 'Microsoft OLE DB Provider for ODBC Drivers', 'ERROR: Charge not in a correct status to delete;\nError while executing the query', None, 0, -2147467259), None)
-2147352567, 'Exception occurred.', (0, 'Microsoft OLE DB Provider for ODBC Drivers', 'ERROR: Charge not in a correct status to delete;\nError while executing the query', None, 0, -2147467259), None
36, 191
(0, 'Microsoft OLE DB Provider for ODBC Drivers', 'ERROR: Charge not in a correct status to delete;\nError while executing the query', None, 0, -214746725
测试代码按预期工作:
testString = "(abc(def)ghij)"
openParenLocation = testString.find('(')
closeParenLocation = testString.rfind(')')
strippedTestString = testString[openParenLocation + 1:closeParenLocation]
openParenLocation = strippedTestString.find('(')
closeParenLocation = strippedTestString.rfind(')')
finalTestString = strippedTestString[openParenLocation + 1:closeParenLocation]
非常感谢。
'Errorstring,则[openParenLocation + 1:closeParenLocation]'???你想通过使用'openParenLocation + 1:closeParenLocation'来做什么? – alfasin
你最初是如何获得/形成'errorString'?它看起来很像一个python元组的'repr'。也许这些数据是作为一个元组来提供的,这将使得处理它变得毫无意义。对于你的问题,你正在为'dbErrorString'指定'strippedString',但是在实际的切片中使用'errorString'而不是'strippedString'。 –
我想剥离外部左括号和右括号以及它们之外的所有内容。原始字符串是从ODBC返回的错误字符串,因为在数据库函数内遇到错误情况。该字符串不是来自Python并且不在元组中。 这项工作的目标是只返回包含在这个长长的gobbledygook内的错误信息:“错误:收费不正确的状态删除”。 –