如何在函数内格式化参数,但也要输出与参数一样多的字符串

时间:2019-07-07 15:19:41

标签: python string python-2.7 function formatting

我是一个初学者,只是在弄乱函数,我想到了下面的代码。我想将字符串的打印次数与a的值一样多,但是我也想在字符串内部格式化参数a的值。任何帮助将不胜感激!

def vhf(a):
    print "So i want this times %d "*a % a

vhf(5)

当我运行它时,出现此错误:

Traceback (most recent call last):
  File "p.py", line 4, in <module>
    vhf(5)
  File "p.py", line 2, in vhf
    print "...So i want this times %d "*a % a
TypeError: not enough arguments for format string

1 个答案:

答案 0 :(得分:2)

当您将字符串乘以a时,所需的格式参数数量将乘以a。您可以将乘法移动到格式化之后以解决问题。

def vhf(a):
    print "So i want this times %d " % a * a

vhf(5)