Python列表在字符串周围生成双qoute并传递给api

2024-09-19 23:41:33 发布

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

Python list在字符串周围加双引号并传递给API,API要求将其作为双引号字符串的列表传递

要传递的API数据:

data = {
    "styles" : styleList
}

当我手动输入:

["A123", "B123", "C131", "D231"]

但不包括:

['A123', 'B123', 'C131', 'D231']

尝试过但没有帮助的事情:

  1. 在字符串周围附加双引号
styleList = ["\"" + style + "\"" for style in styleList]
  1. 用双引号替换单引号
styleList = [style.replace("'","") for style in styleList]
  1. 转储为JSON
styleList = json.dumps(styleList)

所有这些都只对打印有用,而不是通过API


Tags: 数据字符串inapi列表fordatastyle
1条回答
网友
1楼 · 发布于 2024-09-19 23:41:33

您需要列表的字符串表示形式

使用styleList = ["\"" + style + "\"" for style in styleList]可以围绕列表中的项目创建:['a','b'] > ['"a"','"b"']

使用

data = { "styles" : repr(styleList) }`

repr将创建列表的字符串表示:repr()

data = [1,2,3,'tata',8.9]

r = repr(data)                      # "[1, 2, 3, 'tata', 8.9]"

如果你也需要引用数字,请使用

# convert anything to its string representation
r = repr( [str(e) for e in data] )  # "['1', '2', '3', 'tata', '8.9']"

相关问题 更多 >