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

时间:2014-02-03 18:14:02

标签: python

我试图在python中找到一个更大的字符串中的子字符串。我试图找到字符串“每秒请求数:”后找到的文本。看来我对python字符串和python的了解一般都缺乏。

我的错误出现在第3行代码minusStuffBeforeReqPer = output[reqPerIndx[0], len(output)]上,我得到的错误是,在reqPerIndx上没有[0]我正在尝试访问元组,但是我得到了错误{I} {1}}。我试图在int object has no attribute __getitem__字符串中找到reqPerStr的起始索引。

代码

output

2 个答案:

答案 0 :(得分:4)

您必须使用output[begin:end],而不是output[begin, end](这就是切片普通字符串/列表/等的工作原理)。所以:

minusStuffBeforeReqPer = output[reqPerIndx:len(output)]

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

minusStuffBeforeReqPer = output[reqPerIndx:]

通过省略切片的end部分,切片将一直到output的末尾。


在没有[0]的情况下访问元组时出现错误,因为您已经传递了一个元组(即(reqPerIndx, len(output))到切片[...]),并且您收到有关{{1}的错误没有int,因为当你写__getitem__时,你试图获得reqPerIndx[0]的{​​{1}}元素,这是一个整数,但当然没有诸如“整数的第0个元素”之类的东西,因为整数没有元素。


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

output

你可能有更好的运气与正则表达式。我不知道-1的样子,所以我猜对了 - 你应该调整它以匹配reqPerIndx = output.find(reqPerStr) if reqPerIndx != -1: minusStuffBeforeReqPer = ... # etc else: # handle this case separately 中的任何内容。

output

答案 1 :(得分:0)

这两行有错误:

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

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

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

minusStuffBeforeReqPer = output[-1:]

这是字符串中的最后一个字符。

您应该拥有如下代码:

#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结尾的字符串,并获取介于:\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)
相关问题