How do I put a variable inside a string?

前端 未结 8 2271
名媛妹妹
名媛妹妹 2020-11-21 06:05

I would like to put an int into a string. This is what I am doing at the moment:

num = 40
plot.savefig(\'hanning40.pdf\') #problem          


        
8条回答
  •  走了就别回头了
    2020-11-21 06:22

    With the introduction of formatted string literals ("f-strings" for short) in Python 3.6, it is now possible to write this with a briefer syntax:

    >>> name = "Fred"
    >>> f"He said his name is {name}."
    'He said his name is Fred.'
    

    With the example given in the question, it would look like this

    plot.savefig(f'hanning{num}.pdf')
    

提交回复
热议问题