-1
def hello(input, *args):
    s=input.replace('%0','{0}')
    v=s.format(args)
    return v

assert "hello stack"==hello("hello %0","stack")

I am getting ASSERTION ERROR and the output is : "hello ('stack',)" instead of "hello stack".....WHY???

shweta
  • 1
  • 6

1 Answers1

1

In the code that generates the error, you have the following as your function header:

def hello(input, *args):

This will turn args into a tuple of all positional arguments. The code you have pasted in the question does not generate the error:

>>> 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',)"

To make it work, you need to expand the tuple: v = s.format(*args).

I'm not sure what the actual purpose of this code is, because it will only take the first argument; no matter how many actual arguments you sent to the method:

>>> def hello3(input, *args):
...     s = input.replace('%0', '{0}')
...     v = s.format(*args)
...     return v
...
>>> hello3('hello %0', 'stack', 'world')
'hello stack'

This is because the {0} binds to the first argument .format().

Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284