Converting string to tuple without splitting characters

后端 未结 9 1138
逝去的感伤
逝去的感伤 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:47

    This only covers a simple case:

    a = ‘Quattro TT’
    print tuple(a)
    

    If you use only delimiter like ‘,’, then it could work.

    I used a string from configparser like so:

    list_users = (‘test1’, ‘test2’, ‘test3’)
    and the i get from file
    tmp = config_ob.get(section_name, option_name)
    >>>”(‘test1’, ‘test2’, ‘test3’)”
    

    In this case the above solution does not work. However, this does work:

    def fot_tuple(self, some_str):
         # (‘test1’, ‘test2’, ‘test3’)
         some_str = some_str.replace(‘(‘, ”)
         # ‘test1’, ‘test2’, ‘test3’)
         some_str = some_str.replace(‘)’, ”)
         # ‘test1’, ‘test2’, ‘test3’
         some_str = some_str.replace(“‘, ‘”, ‘,’)
         # ‘test1,test2,test3’
         some_str = some_str.replace(“‘”, ‘,’)
         # test1,test2,test3
         # and now i could convert to tuple
         return tuple(item for item in some_str.split(‘,’) if item.strip())
    
    0 讨论(0)
  • 2020-12-02 20:53

    See:

    'Quattro TT'
    

    is a string.

    Since string is a list of characters, this is the same as

    ['Q', 'u', 'a', 't', 't', 'r', 'o', ' ', 'T', 'T']
    

    Now...

    ['Quattro TT']
    

    is a list with a string in the first position.

    Also...

    a = 'Quattro TT'
    
    list(a)
    

    is a string converted into a list.

    Again, since string is a list of characters, there is not much change.

    Another information...

    tuple(something)
    

    This convert something into tuple.

    Understanding all of this, I think you can conclude that nothing fails.

    0 讨论(0)
  • 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)
    
    0 讨论(0)
提交回复
热议问题