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

后端 未结 5 1755
温柔的废话
温柔的废话 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:54

    You can also use str.format() to produce any arbitrary formatting if you're willing to use * magic. To handle the specific case of this question, with a single separator, is actually a little cumbersome:

    >>> bounds = (34.2424, -64.2344, 76.3534, 45.2344)
    >>> "{} {} {} {}".format(*bounds)
    
    34.2424 -64.2344 76.3534 45.2344
    

    A more robust version that handles any length, like join, is:

    >>> len(bounds)*"{} ".format(*bounds)
    

    But the value added is that if you want to extend your formatting to something more involved you've got the option:

    >>> "{} --> | {:>10} | {:>10} | {:>10} |".format(*bounds)
    
    34.2424 --> |   -64.2344 |    76.3534 |    45.2344 |
    

    From here, your string formatting options are very diverse.

提交回复
热议问题