如何在Python中使用多个字符串参数

ili*_*ias -2 python

我想使用%s将两个参数传递给我的字符串.

我试过这个,但它不起作用:

title = "im %s with %s"
title % "programming" % "python"
Run Code Online (Sandbox Code Playgroud)

它给出了这个错误:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: not enough arguments for format string
Run Code Online (Sandbox Code Playgroud)

你有好主意吗?谢谢

NPE*_*NPE 8

正确的语法是:

title = "im %s with %s"
title % ("programming", "python")
Run Code Online (Sandbox Code Playgroud)

%操作需要两个操作数:

  1. 格式字符串在左侧;
  2. 包含所有参数的元组位于右侧(如果只有一个参数,则它可以是标量).


Lev*_*von 5

通过分解这些格式化指令的工作原理,可能最好地理解这个问题.基本思想是%字符串中的每个都意味着需要随后将参数提供给字符串.

例如,这可以工作:

title = "i'm %s with %s" % ('programming', 'python')
Run Code Online (Sandbox Code Playgroud)

和产量

"i'm programming with python"
Run Code Online (Sandbox Code Playgroud)

's' %s表示这是一个字符串的占位符.'d'用于整数,'f'用于浮点数等.还可以指定其他参数.请参阅这些文档.

如果您没有为每个占位符提供足够的物品,则会产生not enough arguments for format string消息.

您的具体示例首先创建一个字符串常量,其中包含两个格式化指令.然后当你使用它时,你将不得不为它提供两个项目.

换一种说法,

title = "i'm %s with %s"
title % ('programming', 'python')
Run Code Online (Sandbox Code Playgroud)

"i'm %s with %s" % ('programming', 'python')
Run Code Online (Sandbox Code Playgroud)