首页 > 解决方案 > python程序获取一个字符串并返回一个列表而不使用像eva()这样的任何builin但是我们可以使用字符串内置函数吗

问题描述

我需要以下解决方案,但我无法获得解决方案 - 需要一个字符串返回一个列表

i/p:  "[(694, 104), (153, 236), (201, 106), (601, 427)]"
o/p: 
(694, 104)
(153, 236)
(201, 106)
(601, 427)

我写了下面的代码-

def convertor(string):
    result = (string.split("  "))[0]
    return result


string1 = "[(694, 104), (153, 236), (201, 106), (601, 427)]"

out=convertor(string1.replace("[","").replace("]",""))
print(out)

我得到的当前输出 --(694, 104), (153, 236), (201, 106), (601, 427) 但我需要上述格式的输出

标签: pythonstringlisttuples

解决方案


您可以添加.replace("), (", ")\n(")如下:

def convertor(string):
    result = (string.split("\n"))
    return result

string1 = "[(694, 104), (153, 236), (201, 106), (601, 427)]"

out=convertor(string1.replace("[","").replace("]","").replace("), (", ")\n("))

for tpl in out:
    print(tuple(tpl))

输出将是:

(694, 104)
(153, 236)
(201, 106)
(601, 427)

推荐阅读