【问题标题】:How to format an argument inside a function but also print the string as many times as the argument如何格式化函数内的参数,但打印字符串的次数与参数一样多
【发布时间】:2023-03-17 10:39:02
【问题描述】:

我是一个初学者,只是在玩弄函数,我想到了下面的代码。我想打印字符串的次数与 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

【问题讨论】:

    标签: python string python-2.7 function formatting


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-23
      • 2021-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-27
      相关资源
      最近更新 更多