sprintf like functionality in Python

后端 未结 11 1863
暖寄归人
暖寄归人 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:04

    Python has a % operator for this.

    >>> a = 5
    >>> b = "hello"
    >>> buf = "A = %d\n , B = %s\n" % (a, b)
    >>> print buf
    A = 5
     , B = hello
    
    >>> c = 10
    >>> buf = "C = %d\n" % c
    >>> print buf
    C = 10
    

    See this reference for all supported format specifiers.

    You could as well use format:

    >>> print "This is the {}th tome of {}".format(5, "knowledge")
    This is the 5th tome of knowledge
    

提交回复
热议问题