【问题标题】:Python: Convert string representative of a string array to a listPython:将代表字符串数组的字符串转换为列表
【发布时间】:2020-04-17 15:11:05
【问题描述】:

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

例如: 邮递员传递的值

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

我尝试过但失败了:

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

给出这个错误:

在处理上述异常期间(无效语法 (, 第 1)) 行,发生了另一个异常:

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

【问题讨论】:

  • 这整件事是“数据”吗:[“bacsr”attd”和,fhhh'''”,”'gehh',uujf“hjjj”“,,,,hhhhh,,”, "1"] 开头刺痛?
  • @SebNik 它在邮递员中作为表单数据传递。 "data" 为键,其值为 ["bacsr "attd" and, fhhh'''","'gehh', uujf "hjjj"",",,,hhhhh,, ","1"]跨度>
  • "data" 为键,其值为 ["bacsr "attd" and, fhhh'''","'gehh', uujf "hjjj"",",,,hhhhh,, ","1"]

标签: python django python-3.x python-2.7 python-requests


【解决方案1】:

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

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

没有\,Python 知道你的字符串结束了,不知道attd 是什么。

PS。对不起,我的英语不太流利。

【讨论】:

    【解决方案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 与您提供的不同,但我无法实现。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-06
      • 1970-01-01
      • 2021-12-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多