How to transform a tuple to a string of values without comma and parentheses

后端 未结 5 1778
温柔的废话
温柔的废话 2020-11-28 11:55

I retrieved data from a sql query by using

bounds = cursor.fetchone()

And I get a tuple like:

(34.2424, -64.2344, 76.3534,         


        
5条回答
  •  佛祖请我去吃肉
    2020-11-28 12:37

    If I've got your message, you are getting tuple of floats, am I right?

    If so, the following code should work:

    In [1]: t = (34.2424 , -64.2344 , 76.3534 , 45.2344)
    
    In [2]: ' '.join([str(x) for x in t])
    Out[2]: '34.2424 -64.2344 76.3534 45.2344'
    

    We're converting every value in tuple to string here, because str.join method can work only with lists of string. If t is a tuple of strings the code will be just ' '.join(t).

    In case you're getting string in format "(34.2424 , -64.2344 , 76.3534 , 45.2344)", you should firstly get rid of unnescessary parthensis and commas:

    In [3]: t = "(34.2424 , -64.2344 , 76.3534 , 45.2344)"
    
    In [4]: t.strip('()')
    Out[4]: '34.2424 , -64.2344 , 76.3534 , 45.2344'
    
    In [5]: numbers = t.strip('()')
    
    In [6]: numbers.split(' , ')
    Out[6]: ['34.2424', '-64.2344', '76.3534', '45.2344']
    
    In [7]: ' '.join(numbers.split(' , '))
    Out[7]: '34.2424 -64.2344 76.3534 45.2344'
    

提交回复
热议问题