sprintf like functionality in Python

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

提交回复
热议问题