Python分离数值

huangapple go评论68阅读模式
英文:

python seperating values

问题

我想要将idcode的值分别定义为不同的字符串。我该如何在Python中使用Selenium和正则表达式(我不完全理解它)来实现这个目标?

英文:

I am getting a response like this id=51555263943&code=q15cd225s6s8 and I want to define the value of the id and the value of the code in separate strings
How can I do this in python selenium maybe with regex(which I don't completely understand it)?

答案1

得分: 2

你可以在'&'值上拆分响应并将返回的列表元素分配给新变量

input = 'id=51555263943&code=q15cd225s6s8'.split('&')

id = input[0].split('=')[1]

code = input[1].split('=')[1]

print(id)
print(code)

输出:

51555263943
q15cd225s6s8
英文:

You can split the response on the '&' value and assign the returned list elements to new variables.

input = 'id=51555263943&code=q15cd225s6s8'.split('&')

id = input[0].split('=')[1]

code = input[1].split('=')[1]

print(id)
print(code)

Output:

51555263943 
q15cd225s6s8

答案2

得分: 2

output 是一个包含你需要的 id 和 code 的列表。

英文:

Assuming the strings always come like that and that you are using regex:

import re
s = 'id=51555263943&code=q15cd225s6s8'
output = re.findall(r'(?<=\=)[^&]+',s,flags=re.IGNORECASE)

output is a list containing the id and the code you need.

答案3

得分: 2

我也会使用split方法基于"&"创建一个列表。然后,我会循环遍历这个列表,并在"="上进行拆分,将这些值存储在一个字典中,以便以后轻松访问。这样,您也可以轻松扩展到更大的响应。

res = 'id=51555263943&code=q15cd225s6s8'
resSplit = res.split('&')

resDict = {}

for i in resSplit:
  i_split = i.split('=')
  resDict[i_split[0]] = i_split[1]

print(resDict)
# 输出
{'id': '51555263943', 'code': 'q15cd225s6s8'}
英文:

I would also use the split method to create a list based on "&".
Afterwards I would loop over the list and do a split on "=" and store these values in a dictionary, so they are easy to access later. This way you can also easily scale to a bigger response.

res = 'id=51555263943&code=q15cd225s6s8'
resSplit = res.split('&')

resDict = {}

for i in resSplit:
  i_split = i.split('=')
  resDict[i_split[0]] = i_split[1]

print(resDict)
>>>> output
{'id': '51555263943', 'code': 'q15cd225s6s8'}

huangapple
  • 本文由 发表于 2023年4月4日 03:56:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/75923324.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定