python格式操作中的歧义
我得到断言错误,输出是:“hello('stack',)”python格式操作中的歧义,python,Python,我得到断言错误,输出是:“hello('stack',)” 生成错误的代码中没有“hello stack”……为什么?,而是将以下内容作为函数头: def hello(input, *args): s=input.replace('%0','{0}') v=s.format(args) return v assert "hello stack"==hello("hello %0","stack") 这将把args转换为所有位置参数的元组。您在问题中粘贴的代码不会生成错
生成错误的代码中没有“hello stack”……为什么?,而是将以下内容作为函数头:
def hello(input, *args):
s=input.replace('%0','{0}')
v=s.format(args)
return v
assert "hello stack"==hello("hello %0","stack")
这将把args
转换为所有位置参数的元组。您在问题中粘贴的代码不会生成错误:
def hello(input, *args):
要使其工作,您需要展开元组:v=s.format(*args)
我不确定这段代码的实际用途是什么,因为它只接受第一个参数;无论您向该方法发送了多少个实际参数:
>>> def hello(input, args):
... s = input.replace('%0', '{0}')
... v = s.format(args)
... return v
...
>>> hello('hello %0', 'stack')
'hello stack'
>>> def hello2(input, *args):
... s = input.replace('%0', '{0}')
... v = s.format(args)
... return v
...
>>> hello2('Hello %0', 'stack')
"Hello ('stack',)"
这是因为
{0}
绑定到第一个参数.format()
FWIW,我无法在Python3.4和on上重现这一点,即不要命名变量input
,这是一个Python函数名没有名称defHello(input,*args)
中是否有星号?这将导致您发布的错误。@unutbu看起来刚才的编辑已经确认:pSo如果您的函数使用了*args
,为什么不将其传递给str.format()
和s.format(*args)
?。可能只想添加它来修复它:v=s.format(*args)
>>> def hello3(input, *args):
... s = input.replace('%0', '{0}')
... v = s.format(*args)
... return v
...
>>> hello3('hello %0', 'stack', 'world')
'hello stack'