sprintf like functionality in Python

后端 未结 11 1798
暖寄归人
暖寄归人 2020-12-23 02:50

I would like to create a string buffer to do lots of processing, format and finally write the buffer in a text file using a C-style sprintf functionality in Pyt

相关标签:
11条回答
  • 2020-12-23 03:12

    To insert into a very long string it is nice to use names for the different arguments, instead of hoping they are in the right positions. This also makes it easier to replace multiple recurrences.

    >>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
    'Coordinates: 37.24N, -115.81W'
    

    Taken from Format examples, where all the other Format-related answers are also shown.

    0 讨论(0)
  • 2020-12-23 03:13

    I'm not completely certain that I understand your goal, but you can use a StringIO instance as a buffer:

    >>> import StringIO 
    >>> buf = StringIO.StringIO()
    >>> buf.write("A = %d, B = %s\n" % (3, "bar"))
    >>> buf.write("C=%d\n" % 5)
    >>> print(buf.getvalue())
    A = 3, B = bar
    C=5
    

    Unlike sprintf, you just pass a string to buf.write, formatting it with the % operator or the format method of strings.

    You could of course define a function to get the sprintf interface you're hoping for:

    def sprintf(buf, fmt, *args):
        buf.write(fmt % args)
    

    which would be used like this:

    >>> buf = StringIO.StringIO()
    >>> sprintf(buf, "A = %d, B = %s\n", 3, "foo")
    >>> sprintf(buf, "C = %d\n", 5)
    >>> print(buf.getvalue())
    A = 3, B = foo
    C = 5
    
    0 讨论(0)
  • 2020-12-23 03:21

    If you want something like the python3 print function but to a string:

    def sprint(*args, **kwargs):
        sio = io.StringIO()
        print(*args, **kwargs, file=sio)
        return sio.getvalue()
    
    >>> x = sprint('abc', 10, ['one', 'two'], {'a': 1, 'b': 2}, {1, 2, 3})
    >>> x
    "abc 10 ['one', 'two'] {'a': 1, 'b': 2} {1, 2, 3}\n"
    

    or without the '\n' at the end:

    def sprint(*args, end='', **kwargs):
        sio = io.StringIO()
        print(*args, **kwargs, end=end, file=sio)
        return sio.getvalue()
    
    >>> x = sprint('abc', 10, ['one', 'two'], {'a': 1, 'b': 2}, {1, 2, 3})
    >>> x
    "abc 10 ['one', 'two'] {'a': 1, 'b': 2} {1, 2, 3}"
    
    0 讨论(0)
  • 2020-12-23 03:23

    Use the formatting operator % : buf = "A = %d\n , B= %s\n" % (a, b) print >>f, buf

    0 讨论(0)
  • 2020-12-23 03:25

    You can use string formatting:

    >>> a=42
    >>> b="bar"
    >>> "The number is %d and the word is %s" % (a,b)
    'The number is 42 and the word is bar'
    

    But this is removed in Python 3, you should use "str.format()":

    >>> a=42
    >>> b="bar"
    >>> "The number is {0} and the word is {1}".format(a,b)
    'The number is 42 and the word is bar'
    
    0 讨论(0)
提交回复
热议问题