sprintf like functionality in Python

后端 未结 11 1864
暖寄归人
暖寄归人 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: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}"
    

提交回复
热议问题