2012-05-19 13 views
-2

我想使用%s将两个参数传递给我的字符串。如何在Python中使用几个字符串参数

我想这一点,但没有奏效:

title = "im %s with %s" 
title % "programming" % "python" 

它给出了这样的错误:

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

你有一个想法? 谢谢

+2

这是你看在你发现有摆在首位了''%运行在同一个地方回答的东西。 –

回答

5

通过分解这些格式化指令的工作方式,可能会最好地理解问题。基本思想是每个%在一个字符串中表示一个参数需要随后提供给字符串。

举例来说,这会工作:

title = "i'm %s with %s" % ('programming', 'python') 

,并产生

"i'm programming with python" 

的 's' 在%s意味着这是一个字符串的占位符。 'd'表示整数,'f'表示浮点数等。还有其他参数可以指定。见these docs

如果您没有为每个占位符提供足够的项目,将会产生not enough arguments for format string消息。

您的具体示例首先创建一个字符串常量,其中包含两个格式指令。那么当你使用它时,你必须为它提供两件物品。

换句话说,

title = "i'm %s with %s" 
title % ('programming', 'python') 

变得

"i'm %s with %s" % ('programming', 'python') 
8

正确的语法是:

title = "im %s with %s" 
title % ("programming", "python") 

%运算符采用两个操作数:

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

谢谢,它的作品! :) – ilias

+0

再次感谢您的解释:) – ilias

1

不是一个真正的答案,但:

您也可以使用这样的:

title = "im %(doing)s with %(with)s" 
title % {'doing': 'programming', 'with': 'python'} 

或:

title = "im %(doing)s with %(with)s" % {'doing': 'programming', 'with': 'python'} 

其中%s,而不是使用%(你的字典键),而不是你在modulo运算符后传递字典的元组。

检查String formatting operations

相关问题