Python TypeError:格式字符串的参数不够。看不出有什么不对劲

时间:2014-04-09 06:16:00

标签: python

我的脚本中有这个python代码。

dataBase = str(request.forms.get('db')) 
data =  "/usr/local/Calpont/mysql/bin/mysql --defaults-file=/usr/local/Calpont/mysql/my.cnf  -u root %s -e \"show tables like \'f_\%s\'\"" %(dataBase)

但是当我运行它时它会给我以下错误: -

TypeError: not enough arguments for format string

任何帮助?

1 个答案:

答案 0 :(得分:3)

您的格式字符串中有两个 %s标记:

... -u root %s -e \"show tables like \'f_\%s\' ...
            ^^                            ^^

但只有一个参数database

您需要有足够的参数来标记数量。最有可能的是,这是一个简单的问题。

  • 如果您尝试使用其他参数,则需要提供该参数,例如... % (dataBase, tableName)
  • 如果您尝试使用文字 %标记,则需要将其转义为%% \%正如你可能在想的那样。

鉴于您使用的是like,我认为第二种可能性最大,因为%是该运算符的通配符。

以下成绩单可能会使问题更加清晰:

pax> python
Python 2.7.3 (default, Mar 14 2014, 11:57:14) 
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.

>>> print "... -u root %s -e \"show tables like \'f_\%s\' ..." %("A")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: not enough arguments for format string

>>> print "... -u root %s -e \"show tables like \'f_\%s\' ..." %("A","B")
... -u root A -e "show tables like 'f_\B' ...

>>> print "... -u root %s -e \"show tables like \'f_%%\' ..." %("A")
... -u root A -e "show tables like 'f_%' ...

>>> _

第一个和第二个命令显示使用两个%s标记需要两个参数。

第三个命令显示如何正确转义字符串中的%