首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在这段代码中,这两行是什么意思?

在这段代码中,这两行是什么意思?
EN

Stack Overflow用户
提问于 2019-03-31 23:28:45
回答 1查看 121关注 0票数 -4

[:http_payload.index("\r\n\r\n")+2]中":“和"+2”是什么意思?在.split("/")[1]中"("/")“和"1”是什么意思

代码语言:javascript
复制
def get_http_headers(http_payload):
    try:
        # split the headers off if it is HTTP traffic
        headers_raw = http_payload[:http_payload.index("\r\n\r\n")+2]

        # break out the headers
        headers = dict(re.findall(r"(?P<name>.*?): (? P<value>.*?)\r\n", headers_raw))

    except:
        return None

    return headers

def extract_image(headers, http_payload):
    image = None
    image_type = None

    try:
        if "image" in headers["Content-Type"]:
            # grab the image type and image body
            image_type = headers["Content-Type"].split("/")[1]

            image = http_payload[http_payload.index("\r\n\r\n")+4:]



            except:
                pass
    except:
        return None, None

    return image, image_type
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-04-01 02:36:01

http_payload[:http_payload.index("\r\n\r\n")+2] slices字符串http_payload,以便只保留字符串的头部,直到第一次出现"\r\n\r\n“和第一个"\r\n”。字符串的.index()方法将返回该模式在字符串中首次出现的索引。

示例:

代码语言:javascript
复制
test = "abcdefg"
# slicing:
print(test[1:3])  # will output 'bc'

# index:
print(test.index('bc'))  # will output 1 (index of start of substring 'bc')

# either start or end (or both) of the slice can be left out, so the following is equivalent:
print(test[:2] == test[0:2])  # will output True

.split("/")[1]将以"/“字符拆分一个字符串,并返回一个列表,从中可以访问索引为1的项。有关示例,请参阅以下代码:

代码语言:javascript
复制
test = "/this/is/a/path"
print(test.split("/"))  # will output ["this", "is", "a", "path"]
print(test.split("/")[0])  # will output "is" since element of index 1 of the resulting list is accessed.
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55442464

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档