如何在字符串中放置变量?

时间:2010-06-02 19:05:53

标签: python string variables

我想将int放入string。这就是我现在正在做的事情:

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

我必须为几个不同的数字运行程序,所以我想做一个循环。但是插入这样的变量不起作用:

plot.savefig('hanning', num, '.pdf')

如何将变量插入Python字符串?

8 个答案:

答案 0 :(得分:377)

哦,很多很多方面......

字符串连接:

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

转换说明符:

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

使用局部变量名称:

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

使用str.format()

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

使用f-strings:

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

使用string.Template

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

答案 1 :(得分:149)

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

%运算符在跟随字符串时允许您通过格式代码(在本例中为%d)将值插入到该字符串中。有关更多详细信息,请参阅Python文档:

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

答案 2 :(得分:95)

在Python 3.6中使用the introduction of formatted string literals(简称“f-strings”),现在可以用更简洁的语法编写它:

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

通过问题中给出的示例,它看起来像这样

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

答案 3 :(得分:13)

不确定您发布的所有代码到底是什么,但要回答标题中提出的问题,您可以使用+作为普通字符串连接函数以及str()。

"hello " + str(10) + " world" = "hello 10 world"

希望有所帮助!

答案 4 :(得分:5)

通常,您可以使用以下方法创建字符串:

stringExample = "someString " + str(someNumber)
print(stringExample)
plot.savefig(stringExample)

答案 5 :(得分:3)

我需要扩展版本:我需要生成一系列文件名为'file1.pdf','file2.pdf'等,而不是在字符串中嵌入单个数字。它是如何工作的:

['file' + str(i) + '.pdf' for i in range(1,4)]

答案 6 :(得分:2)

如果您想将多个值放入字符串中,可以使用format

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

将导致字符串hanning123.pdf。这可以用任何数组来完成。

答案 7 :(得分:0)

您只需使用

将numer变量转换为字符串
switch (m.WParam.ToInt64() & 0xfff0)
相关问题