Reputation:
I create a method to print some stuff:
def my_print(*str1):
print '---------------'
print str1
print '---------------'
my_print('1fdsfd %s -- %s' % (12, 18))
which gives me
---------------
('1fdsfd 12 -- 18',)
---------------
Why do I have these extra (
and )
and even ,
and how do I get rid of them?
Upvotes: 1
Views: 54
Reputation: 251051
The reason is due to *
the str1
is converted into a tuple inside the my_print
function, you can either remove the *
or use print str1[0]
.
When a *
is used in functions definition then it behave as a collector, and collects all the positional arguments passed to function in a tuple.
>>> def func(*a):
... print type(a)
... print a
...
>>> func(1)
<type 'tuple'>
(1,)
>>> func(1,2,3)
<type 'tuple'>
(1, 2, 3)
Working version of your code:
def my_print(str1):
print '---------------'
print str1
print '---------------'
my_print('1fdsfd %s -- %s' % (12, 18))
or :
def my_print(*str1):
print '---------------'
print str1[0]
print '---------------'
my_print('1fdsfd %s -- %s' % (12, 18))
Upvotes: 2
Reputation: 133624
Since you are unpacking all the arguments given to your function with the splat (*
) operator, you are getting a tuple of arguments saved to str1
eg.
>>> my_print('a', 'b')
---------------
('a', 'b')
---------------
Then you are simply printing the tuple of arguments, it seems like you don't need the splat since you only have str1
so just remove it and it works fine.
Upvotes: 0
Reputation: 60004
Remove the *
and use str.format()
instead:
mytuple = (12, 18)
my_print('1fdsfd {0} -- {1}'.format(*mytuple)) # I've used the * here to unpack the tuple.
As others have pointed out, it converts str1
into a tuple.
Upvotes: 0