list of tuple of string to return in list in python

前端 未结 3 839
梦毁少年i
梦毁少年i 2021-01-26 11:54

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)]"         


        
3条回答
  •  爱一瞬间的悲伤
    2021-01-26 12:42

    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)
    

提交回复
热议问题