How do I put a variable inside a string?

前端 未结 8 2273
名媛妹妹
名媛妹妹 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')
    
    0 讨论(0)
  • 2020-11-21 06:33

    I had a need for an extended version of this: instead of embedding a single number in a string, I needed to generate a series of file names of the form 'file1.pdf', 'file2.pdf' etc. This is how it worked:

    ['file' + str(i) + '.pdf' for i in range(1,4)]
    
    0 讨论(0)
  • 2020-11-21 06:34
    plot.savefig('hanning(%d).pdf' % num)
    

    The % operator, when following a string, allows you to insert values into that string via format codes (the %d in this case). For more details, see the Python documentation:

    https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting

    0 讨论(0)
  • 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()))
    
    0 讨论(0)
  • 2020-11-21 06:37

    You just have to cast the num varriable into a string using

    str(num)
    
    0 讨论(0)
  • 2020-11-21 06:38

    If you would want to put multiple values into the string you could make use of format

    nums = [1,2,3]
    plot.savefig('hanning{0}{1}{2}.pdf'.format(*nums))
    

    Would result in the string hanning123.pdf. This can be done with any array.

    0 讨论(0)
提交回复
热议问题