如何将变量放入字符串中? [英] How do I put a variable inside a string?

查看:106
本文介绍了如何将变量放入字符串中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将 int 放入 string.这就是我目前正在做的:

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 line

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

I have to run the program for several different numbers, so I'd like to do a loop. But inserting the variable like this doesn't work:

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

如何在 Python 字符串中插入变量?

How do I insert a variable into a Python string?

推荐答案

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

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

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

这篇关于如何将变量放入字符串中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆