如何在Python中的String中放置一个变量?

Gis*_*ish 218 python string variables

我想int加入一个string.这就是我现在正在做的事情:

num = 40
plot.savefig('hanning40.pdf') #problem line
Run Code Online (Sandbox Code Playgroud)

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

plot.savefig('hanning', num, '.pdf')
Run Code Online (Sandbox Code Playgroud)

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

Dan*_*all 432

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

字符串连接:

plot.savefig('hanning' + str(num) + '.pdf')
Run Code Online (Sandbox Code Playgroud)

转换说明符:

plot.savefig('hanning%s.pdf' % num)
Run Code Online (Sandbox Code Playgroud)

使用局部变量名称:

plot.savefig('hanning%(num)s.pdf' % locals()) # Neat trick
Run Code Online (Sandbox Code Playgroud)

使用format():

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

使用f字符串:

plot.savefig(f'hanning{num}.pdf') # added in Python 3.6
Run Code Online (Sandbox Code Playgroud)

使用string.Template:

plot.savefig(string.Template('hanning${num}.pdf').substitute(locals()))
Run Code Online (Sandbox Code Playgroud)

  • 要使用带有多个参数的格式字符串运算符,可以使用元组作为操作数:`'foo%d,bar%d'%(foo,bar)`. (14认同)
  • 你的整洁技巧也适用于新的格式语法:`plot.savefig('hanning {num} s.pdf'.format(**locals()))` (12认同)
  • 随着Python 3.6中f字符串的引入,现在可以将其写为`plot.savefig(f'hanning {num} .pdf')`.我添加了这个信息的答案. (12认同)
  • @MAChitgarha:一厢情愿的想法,但对于随着时间的推移而发展的语言来说,这可能是不可能的。 (3认同)
  • f 字符串是*在可能的情况下*的首选方式:即,当可以立即将格式设置为文字模板时。当需要保存模板并重新使用它或推迟使用它时,f 字符串不起作用。在这些情况下,请使用“.format”方法。 (2认同)

Amb*_*ber 156

plot.savefig('hanning(%d).pdf' % num)
Run Code Online (Sandbox Code Playgroud)

%运营商,下面的字符串时,允许你插入值到通过格式代码的字符串(%d在这种情况下).有关更多详细信息,请参阅Python文档:

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

  • 请注意,自Python 3.1起,不推荐使用`%`运算符.新的首选方法是使用[PEP 3101](https://www.python.org/dev/peps/pep-3101/)中讨论的`.format()`方法,并在Dan McDougall的回答中提到. (26认同)
  • '%' 运算符并未被弃用 - 它只是现在不是首选方式。 (2认同)

joe*_*lom 106

通过在Python 3.6中引入格式化的字符串文字(简称"f-strings"),现在可以用更简洁的语法编写它:

>>> name = "Fred"
>>> f"He said his name is {name}."
'He said his name is Fred.'
Run Code Online (Sandbox Code Playgroud)

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

plot.savefig(f'hanning{num}.pdf')
Run Code Online (Sandbox Code Playgroud)

  • 看来[f-strings与多行字符串兼容](/sf/answers/3291644261/). (3认同)

gog*_*n13 16

不确定你发布的所有代码究竟是什么,但是为了回答标题中提出的问题,你可以使用+作为普通的字符串concat函数以及str().

"hello " + str(10) + " world" = "hello 10 world"
Run Code Online (Sandbox Code Playgroud)

希望有所帮助!

  • 虽然这个答案是正确的,但应该避免使用`+`构建字符串,因为它非常昂贵 (6认同)

Yeh*_*tan 6

通常,您可以使用以下命令创建字符串:

stringExample = "someString " + str(someNumber)
print(stringExample)
plot.savefig(stringExample)
Run Code Online (Sandbox Code Playgroud)


Jon*_*n R 6

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

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

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


归档时间:

查看次数:

644471 次

最近记录:

6 年,3 月 前