Python:将代表字符串数组的字符串转换为列表

2024-10-03 11:23:29 发布

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

我试图将代表字符串数组的字符串转换为python列表,该字符串数组通过postman传递给API端点时,数组项中包含双引号、单引号和逗号。(我正在使用Python 3.6)

例: 邮递员传递的价值

"data":["bacsr "attd" and, fhhh'''","'gehh', uujf "hjjj"",",,,hhhhh,, ","1"]
  • 元素1=“bacsr”附件“和,fhhh”
  • 元素2=“'gehh',uujf”hjjj”
  • 元素3=“,,hhhhh,,”
  • 元素4=“1”

我尝试过但失败了:

post_values = request.data['data']
post_values = ast.literal_eval(post_values)

给出此错误:

During handling of the above exception (invalid syntax (, line 1)), another exception occurred:

如何将其转换为具有相关字符串转义的4元素列表


Tags: 字符串元素列表dataexception代表数组post
2条回答

希望这足够清楚

import re

data = """\
"data":["bacsr "attd" and, fhhh'''","'gehh', uujf "hjjj"",",,,hhhhh,, ","1"]\
"""

data = data.replace('[','').replace(']','')

# regular expression to split out quoted or unquoted tokens in data string into individual groups
pat = re.compile(r'(?:")?([^"]*)(?:(?(1)"|))')
groups = [* filter(None, pat.split(data))]

l = ['']
for token in groups[2:]:
     if token == ',':
         l.append('')
     else:
         l[-1] += token

post_values = {groups[0] : l} # construct the result dict

print(post_values)

print()
for v in post_values['data']:
    print(v)

输出:

{'data': ["bacsr attd and, fhhh'''", "'gehh', uujf hjjj", ',,,hhhhh,, ', '1']}

bacsr attd and, fhhh'''
'gehh', uujf hjjj
,,,hhhhh,,
1

注意:元素2和你给出的不一样,但我不能做到这一点

当您写入:"bacsr "attd" and, fhhh'''"时,字符串以第一个双引号开始,以第二个双引号结束,attd超出字符串范围。 要使用引号和双引号,必须在前面加一个\。像这样:

"bacsr \"attd\" and, fhhh\'\'\'"

如果没有\,Python会理解字符串结束了,而不知道什么是attd

对不起,我的英语不流利

相关问题 更多 >