简体   繁体   中英

list of tuple of string to return in list in 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("]","")))

You can use ast.literal_eval

import ast
arr = ast.literal_eval("[(694, 104), (153, 236), (201, 106), (601, 427)]")
for ele in arr:
    print(ele)

Output

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

How about using 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))

The easiest way to achieve that would be using eval (you don't need to import anything):

eval(string1)
# -> [(694, 104), (153, 236), (201, 106), (601, 427)]

But, if you really want to use just str and list methods:

def convertor(string):
    result = string.strip('[)]').split('), ')
    result = [s+')' for s in result]
    return result

string1 = "[(694, 104), (153, 236), (201, 106), (601, 427)]"
print(convertor(string1))
# -> ['(694, 104)', '(153, 236)', '(201, 106)', '(601, 427)']

To reproduce the exact output:

for item in convertor(string1):
    print(item)
(694, 104)
(153, 236)
(201, 106)
(601, 427)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM