如何将包含数组形式的字符串转换为数组?

时间:2016-10-14 11:57:26

标签: python arrays django string

我收到了这种形式的字符串

payload = ["Text 1", "Text 2"]

我想使用Text 2作为对象。我该如何退货?

更新 我正在创建一个返回generic template Facebook API的函数。 第一个payload效果很好,但我希望在第二个string(结果)中返回objectpayload

button = [
            {
                "type": "postback",
                "title": "Buy item",
                "payload": "Buy this item: " + (product['id'])
            },
            {
                "type": "postback",
                "title": "Add to wishlist",
                "payload": result
            }
        ]

我的第二个有效负载应该如下所示:

payload = {
            'Order_item',
            product['title']
        }

因为我收到了此错误[buttons][1][payload] must be a UTF-8 encoded string所以我确实将其转换了,并以此格式返回 STRING ["Order_item", "Ledverlichting Fiets Blauw"]

因为我希望当Facebook用户点击回发(添加到心愿单)时,product['title']值将保存在Django数据库中。 product['title']是上述问题中的Text 2

4 个答案:

答案 0 :(得分:3)

你需要拆分字符串然后修剪并继续拆分/修剪以获得你想要在列表中的所有部分

s = 'payload = ["Text 1", "Text 2"]'
items = s.strip()[1:-1]
#if 'payload = ' is also part of string you need to split it also by '=' so it would be:
#items = s.split("=").strip()[1:-1] 
l = [item.strip()[1:-1] for item in items.split(",")]

然后你有你可以迭代的字符串列表,得到第n项等等

the_item = l[1]
return the_item

答案 1 :(得分:1)

假设你想要一个字符串对象,你可以得到数组中的特定索引(第一个spot = 0,第二个spot = 1等)。

您可以像这样保存数组中包含的字符串对象:

payload = ["Text 1", "Text 2"]
s = payload[1]

并且你可以返回s对象。

答案 2 :(得分:0)

你可以尝试:

>>> payload = ["t1", "t2"]
>>> t2 = [1,2]
>>> eval(payload[1])
[1, 2]

答案 3 :(得分:0)

我有一个严格列表格式的字符串,只是通过eval()工作。