How do I put a variable inside a string?

前端 未结 8 2286
名媛妹妹
名媛妹妹 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:34

    Oh, the many, many ways...

    String concatenation:

    plot.savefig('hanning' + str(num) + '.pdf')
    

    Conversion Specifier:

    plot.savefig('hanning%s.pdf' % num)
    

    Using local variable names:

    plot.savefig('hanning%(num)s.pdf' % locals()) # Neat trick
    

    Using str.format():

    plot.savefig('hanning{0}.pdf'.format(num)) # Note: This is the new preferred way
    

    Using f-strings:

    plot.savefig(f'hanning{num}.pdf') # added in Python 3.6
    

    Using string.Template:

    plot.savefig(string.Template('hanning${num}.pdf').substitute(locals()))
    

提交回复
热议问题