python程序接受一个字符串并返回一个列表,而不使用任何类似于eva()的内置函数,但是我们可以使用字符串内置函数吗
我需要下面的解决方案,但我无法获得解决方案-takes字符串返回列表python程序接受一个字符串并返回一个列表,而不使用任何类似于eva()的内置函数,但是我们可以使用字符串内置函数吗,python,string,list,tuples,Python,String,List,Tuples,我需要下面的解决方案,但我无法获得解决方案-takes字符串返回列表 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 resu
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)
我得到的电流输出--(694104),(153236),(201106),(601427)
但是我需要上述格式的输出您可以添加。替换(“),(“,”)\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)
非常感谢。但当我写打印(打印)时它正在显示。它应该是元组类型,对吗?@AshishKumar我已经更新了answer@AshishKumar请注意,在这种特殊情况下,将字符串转换为元组是绝对无用的。如果您愿意,您可以将所有字符串转换为元组。是否有其他解决方案来获得上述内容output@AshishKumar可能存在无限解。你在寻找什么?这样一个字符串的来源是什么?为什么你只能使用字符串方法?在这种情况下,你基本上必须编写某种类型的解析器。请不要重新发布相同的问题是的,你是对的