要在python列表中返回的字符串的元组列表 [英] list of tuple of string to return in list in python
本文介绍了要在python列表中返回的字符串的元组列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
编写一个函数,该函数采用给定格式的字符串返回以下给定格式的列表
write a function which takes a string in the format given returns a list in given below format
input: "[(694, 104), (153, 236), (201, 106), (601, 427)]"
o/p:
(694, 104)
(153, 236)
(201, 106)
(601, 427)
我写了下面的代码,但没有得到正确的输出:
i have written the below code but not getting proper output:
def convertor(string):
result = (string.split(" "))[0]
return result
string1 = "[(694, 104), (153, 236), (201, 106), (601, 427)]"
print(convertor(string1.replace("[","").replace("]","")))
推荐答案
如何使用 ast.literal_eval
:
import ast
def convertor(string):
return ast.literal_eval(string)
string1 = "[(694, 104), (153, 236), (201, 106), (601, 427)]"
print(convertor(string1))
这篇关于要在python列表中返回的字符串的元组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文