Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 从可能更改顺序的字符串中提取值_Python 3.x - Fatal编程技术网

Python 3.x 从可能更改顺序的字符串中提取值

Python 3.x 从可能更改顺序的字符串中提取值,python-3.x,Python 3.x,我从API调用返回了一个子字符串: in_string="JID=1234; path=/demand; HttpOnly; Secure, OPU=; expires=Thu, 01-Jan-1970 01:00:00 GMT; path=/Demand; secure, OA_OS=$66+Y=; expires=Tue, 04-Mar-1990 15:55:22 GMT; path=/; secure" 我需要一种可靠的方法来始终提取“1234”,因为我当前的解决方案看起来并不优雅,而且

我从API调用返回了一个子字符串:

in_string="JID=1234; path=/demand; HttpOnly; Secure, OPU=; expires=Thu, 01-Jan-1970 01:00:00 GMT; path=/Demand; secure, OA_OS=$66+Y=; expires=Tue, 04-Mar-1990 15:55:22 GMT; path=/; secure"
我需要一种可靠的方法来始终提取“1234”,因为我当前的解决方案看起来并不优雅,而且在字符串改变顺序时也无法处理:

in_string.split(';')[0].replace('JID=','')
有更好的办法吗


谢谢,

您考虑过使用regex吗

import re

in_string="JID=1234; path=/demand; HttpOnly; Secure, OPU=; expires=Thu, 01-Jan-1970 01:00:00 GMT; path=/Demand; secure, OA_OS=$66+Y=; expires=Tue, 04-Mar-1990 15:55:22 GMT; path=/; secure"

JID_number_pattern = re.compile(r'JID=\d{1,}')

JID_number = re.search(JID_number_pattern,in_string)
if JID_number:
   print (JID_number.group(0).replace('JID=',''))
   # output
   1234

您只需搜索字符串以查找JID,然后删除后面的字符(the=),然后在字符为数字时执行。这是一个相当宽泛的问题。@ck3mp答案对你有帮助吗?