python字符串操作,在字符串中查找子字符串

2024-10-03 17:22:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在python中找到一个较大字符串中的子字符串。我试图找到字符串“Requests per second:”后出现的文本。我对python字符串和python的一般知识似乎是缺乏的。在

我的错误出现在第三行代码minusStuffBeforeReqPer = output[reqPerIndx[0], len(output)],我得到一个错误:如果reqPerIndx上没有[0],我试图访问一个元组,但是有了这个错误,我得到了int object has no attribute __getitem__。我试图在output字符串中找到reqPerStr开头的索引。在

代码

#output contains the string reqPerStr.
reqPerStr = "Requests per second:"
reqPerIndx = output.find(reqPerStr)
minusStuffBeforeReqPer = output[reqPerIndx[0], len(output)]
eolIndx = minusStuffBeforeReqPer.find("\n")
semiColIndx = minusStuffBeforeReqPer.find(":")
instanceTestObj.reqPerSec = minusStuffBeforeReqPer[semiColIndx+1, eolIndx]

Tags: 字符串代码文本outputlen错误findrequests
2条回答

这两行有错误:

minusStuffBeforeReqPer = output[reqPerIndx[0], len(output)]
instanceTestObj.reqPerSec = minusStuffBeforeReqPer[semiColIndx+1, eolIndx]

您必须使用:来创建一个范围。start:end。在

可以省略最后一个参数以到达结尾,也可以忽略第一个参数以忽略开头。参数也可以是负数。由于find可能返回-1,因此您必须以不同的方式处理它,因为如果找不到字符串,您将得到:

^{pr2}$

它是字符串中的最后一个字符。在

您应该具有如下所示的代码:

#output contains the string reqPerStr.
reqPerStr = "Requests per second:"
reqPerIndx = output.find(reqPerStr)
if reqPerIndx != -1:
    minusStuffBeforeReqPer = output[reqPerIndx[0]:]
    eolIndx = minusStuffBeforeReqPer.find("\n")
    semiColIndx = minusStuffBeforeReqPer.find(":")

    if eolIndx > semiColIndx >= 0:

        instanceTestObj.reqPerSec = minusStuffBeforeReqPer[semiColIndx+1:eolIndx]

这很好,但是,你应该用正则表达式来修改代码。据我所知,您确实希望匹配以reqPerStr开头、以\n结尾的字符串,并获得介于:和{}之间的所有内容。在

你可以这样做:

"Requests per second:(.*)\n"

你最终会得到:

import re

reqPerIndx = output.find(reqPerStr)

match = re.match("Requests per second:(.*)\n", output)
if match:
    instanceTestObj.reqPerSec = match.group(1)

如果要查找所有匹配项,可以执行以下操作:

for match in re.finditer("Requests per second:(.*)", output)
    instanceTestObj.reqPerSec = match.group(1)

必须使用output[begin:end],而不是output[begin, end](这就是对普通字符串/列表/等进行切片的语法)。所以:

minusStuffBeforeReqPer = output[reqPerIndx:len(output)]

然而,这是多余的。所以你应该这样做:

^{pr2}$

通过省略片段的end部分,该片段将一直走到output的末尾。在


访问不带[0]的元组时会出现错误,因为您已经将一个元组(即(reqPerIndx, len(output))传递给了切片{}),并且您得到了一个关于int没有{}的错误,因为当您编写reqPerIndx[0]时,您试图获得reqPerIndx的第{}个元素,这是一个整数,但当然没有这样的事情“整数的第0个元素”,因为整数没有元素。在


正如@AshwiniChaudhary在评论中指出的那样,str.find如果找不到子字符串,-1将返回{}。如果你确定你要找的东西总会在output中找到,我想你不需要处理-1的情况,但无论如何,这样做可能是个好主意。在

reqPerIndx = output.find(reqPerStr)
if reqPerIndx != -1:
    minusStuffBeforeReqPer = ...
    # etc
else:
    # handle this case separately

使用regex可能会有更好的运气。我不知道output是什么样子,所以我只是猜测-你应该调整它来匹配output中的内容。在

>>> import re
>>> re.findall(r'(?:Requests per second:)\s*(\d+)', "Requests: 24")
[]
>>> re.findall(r'(?:Requests per second:)\s*(\d+)', "Requests per second: 24")
['24']

相关问题 更多 >