Converting string to tuple without splitting characters

后端 未结 9 1169
逝去的感伤
逝去的感伤 2020-12-02 19:49

I am striving to convert a string to a tuple without splitting the characters of the string in the process. Can somebody suggest an easy method to do this. Need a one liner.

9条回答
  •  独厮守ぢ
    2020-12-02 20:56

    I use this function to convert string to tuple

    import ast
    
    def parse_tuple(string):
        try:
            s = ast.literal_eval(str(string))
            if type(s) == tuple:
                return s
            return
        except:
            return
    

    Usage

    parse_tuple('("A","B","C",)')  # Result: ('A', 'B', 'C')
    



    In your case, you do

    value = parse_tuple("('%s',)" % a)
    

提交回复
热议问题