python字符串切片方式取倒数两个_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]

非常感谢你。

解决方案

看起来像这行:

dbErrorString = errorString[openParenLocation + 1:closeParenLocation]

相反,应为:

dbErrorString = strippedString[openParenLocation + 1:closeParenLocation]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值