How to insert a variable inside a String in Python?

How to insert a variable inside a String in Python?

Asked on October 26, 2018 in String.
Add Comment


  • 3 Answer(s)

    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())
    

    Using format():

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

    Using string.Template:

    plot.savefig(string.Template('hanning${num}.pdf').substitute(locals()))
    
    Answered on October 26, 2018.
    Add Comment

    Use this code to insert a variable inside a String in Python:

    plot.savefig(f'hanning{num}.pdf')
    
    
    Answered on October 26, 2018.
    Add Comment
    plot.savefig('hanning(%d).pdf' % num)
    

      The % operator, at which the string, allows the user to the insert values into the string via format codes (the %d in this case).

    Answered on October 26, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.