Print prints some extra signs - python

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?

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))

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.

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.

Related

Remove the trailing comma when format string with tuples

I'm doing string formatting with tuples:
a = (1,2,3)
s = f"something in {a}"
print(s)
'something in (1, 2, 3)'
Everything is fine until I encounter a single-element tuple, which gives:
a = (1,)
s = f"something in {a}"
'something in (1,)'
what I actually want is:
'something in (1)'
How do I make tuple string formatting behaves consistently and remove the trailing comma?
You could use your own formatting logic, e.g.
a = (1,2,3)
s = ','.join([str(x) for x in a])
print(s) # 1,2,3
a = (1,)
s = ','.join([str(x) for x in a])
print(s) # 1
Python have 2 magic methods for formatting values: __str__ and __repr__.
__str__ may return any string, but __repr__ must return string that can be passed to eval and recreate value. It's not required, but you should do it. print tries to use __str__ if it's overriden, otherwise it uses __repr__. This means that you can use eval(repr(some_value)) to clone value, because most builtin types have overridden __repr__ properly. That's why you get trailing comma when formatting (1,).
If you really want to format tuple without trailing comma then use
def format_tuple(value):
return "(" + ",".join(repr(v) for v in value) + ")"
# (1,) -> "(1)"
# () -> "()"
# (1, 2, 3,) -> "(1, 2, 3)"
# (1, 2, 3) -> "(1, 2, 3)"
You can use regex:
import re
tuple = (1,)
s = "something in " + re.sub(r',(?=\))', '', str(tuple))
print(s)
Result:
something in (1)
You don't need any for loop etc.
Based on #Tim Biegeleisen's answer:
a = (1,)
s = f"something in ({','.join([str(x) for x in a])})"
print(s)
'something in (1)'

Python convert list of one element into string with bracket

How to convert python list containing one element to string with bracket?
For more than one element, its easy for me to just just use tuple(list['a','b']) which returns as tuple ('a','b') but if element is one, it returns as ('a',) but rather I want to return ('a')
sample:
mylist = ["a", " b"]
print tuple([s.strip() for s in mylist])
>> ('a', 'b')
mylist = ["a"]
print tuple([s.strip() for s in mylist])
>> ('a', ) #rather I want to return ('a')
Avoid relying on default __repr__() method, to format strings, they might change.
Be explicit about your intent instead
print "('" + "', '".join(mylist) + "')"
>>> ('a') == 'a'
True
If you're not going to use a single element tuple, then the parenthesis are only grouping parenthesis (not a container), and they won't stick like you want them to, except you include them as part of the string with a or define a custom print function.
With the custom print function, you get to keep the conversion from list to tuple (i.e. t = tuple(mylist)) as is and also use the single element tuple as is:
def tuple_print(t):
print(str(t).replace(',', '') if len(t) == 1 else t)
Trials:
>>> def tuple_print(t):
... print(str(t).replace(',', '') if len(t) == 1 else t)
...
>>> mylist = ["a"]
>>> t = tuple(mylist)
>>> t
('a',)
>>> tuple_print(t)
('a')
>>> t = ('a', 'b')
>>> tuple_print(t)
('a', 'b')

How to properly convert list of one element to a tuple with one element

>>> list=['Hello']
>>> tuple(list)
('Hello',)
Why is the result of the above statements ('Hello',) and not ('Hello')?. I would have expected it to be the later.
You've got it right. In python if you do:
a = ("hello")
a will be a string since the parenthesis in this context are used for grouping things together. It is actually the comma which makes a tuple, not the parenthesis (parenthesis are just needed to avoid ambiguity in certain situations like function calls)...
a = "Hello","goodbye" #Look Ma! No Parenthesis!
print (type(a)) #<type 'tuple'>
a = ("Hello")
print (type(a)) #<type 'str'>
a = ("Hello",)
print (type(a)) #<type 'tuple'>
a = "Hello",
print (type(a)) #<type 'tuple'>
And finally (and most direct for your question):
>>> a = ['Hello']
>>> b = tuple(a)
>>> print (type(b)) #<type 'tuple'> -- It thinks it is a tuple
>>> print (b[0]) #'Hello' -- It acts like a tuple too -- Must be :)

significance of using print() in python

What is the difference between using print() and not using it.
For example, say a = ("first", "second", "third'), what is the difference between
print (a[0] a[2])
and
a[0] a[2]
?
>>> s = 'foo'
>>> s
'foo'
>>> print s
foo
When you type any expression into the Python interpreter, if said expression returns a value, the interpreter will output that value's representation, or repr. reprs are primarily used for debugging, and are intended to show the value in a way that is useful for the programmer. A typical example of a value's repr is how repr('foo') would output 'foo'.
When you use print, you aren't returning a value and so the interpreter is not actually outputting anything; instead, print is writing the value's str to sys.stdout (or an alternative stream, if you specify it with the >> syntax, e.g. print >>sys.stderr, x). strs are intended for general output, not just programmer use, though they may be the same as repr. A typical example of a value's str is how str('foo') would output foo.
The difference between what the interpreter does and what print comes more into play when you write modules or scripts. print statements will continue to produce output, while expression values are not output unless you do so explicitly. You can still output a value's repr, though: print repr(value)
You can also control str and repr in your own objects:
>>> class MyThing(object):
... def __init__(self, value):
... self.value = value
... def __str__(self):
... return str(self.value)
... def __repr__(self):
... return '<MyThing value=' + repr(self.value) + '>'
...
>>> mything = MyThing('foo')
>>> mything
<MyThing value='foo'>
>>> print mything
foo
In interactive mode, the difference is negligible, as the other answers indicate.
However, in a script, print a[0] will actually print output to the screen, while just a[0] will return the value, but that has no visible effect.
For example, consider the following script, printtest.py:
myList = ["first", "second", "third"]
print "with print:", myList[0], myList[2]
"without print:", myList[0], myList[2]
If you run this script in a terminal (python printtest.py), the output is:
with print: first third
>>> a=("first","second")
>>> print a[0],a[1]
first second
>>> a[0],a[1]
('first', 'second')
you can do this
>>> print (a[0], a[2], a[3])
('first', 'second', 'third')
try it :)
print() and not using it?
print prints value (What I mean is in following example, read comets I added):
>>> print a[1]
second # prints without '
>>> a[1]
'second' # prints with '
more useful:
print:
>>> print "a\nb"
a # print value
b
but interpreter
>>> "a\na" # raw strings
'a\na'
that is raw:
>>> print repr("a\na")
'a\na'
difference: print (a[0] a[2]) and a[0] a[2]?
This print two elements of a tuple. as below
>>> print a[0], a[2]
first third
this is similar to print two strings like below:
>>> print "one", "two"
one two
[second]
Where as this first create a tuple (a[0], a[2]) then that will be printed
>>> print (a[0], a[2])
('first', 'third')
first make a tuple of 2 strings then print that like below:
>>> print ("one", "two")
('one', 'two')
Additionally, if you add , then it makes a tuple:
simple string
>>> a[0]
'first'
and this is tuple:
>>> a[0],
('first',)
similarly,
>>> a[0], a[1]
('first', 'second')

Printing tuple with string formatting in Python

So, i have this problem.
I got tuple (1,2,3) which i should print with string formatting.
eg.
tup = (1,2,3)
print "this is a tuple %something" % (tup)
and this should print tuple representation with brackets, like
This is a tuple (1,2,3)
But I get TypeError: not all arguments converted during string formatting instead.
How in the world am I able to do this? Kinda lost here so if you guys could point me to a right direction :)
>>> # Python 2
>>> thetuple = (1, 2, 3)
>>> print "this is a tuple: %s" % (thetuple,)
this is a tuple: (1, 2, 3)
>>> # Python 3
>>> thetuple = (1, 2, 3)
>>> print(f"this is a tuple: %s" % (thetuple,))
this is a tuple: (1, 2, 3)
Making a singleton tuple with the tuple of interest as the only item, i.e. the (thetuple,) part, is the key bit here.
Note that the % syntax is obsolete. Use str.format, which is simpler and more readable:
t = 1,2,3
print 'This is a tuple {0}'.format(t)
Many answers given above were correct. The right way to do it is:
>>> thetuple = (1, 2, 3)
>>> print "this is a tuple: %s" % (thetuple,)
this is a tuple: (1, 2, 3)
However, there was a dispute over if the '%' String operator is obsolete. As many have pointed out, it is definitely not obsolete, as the '%' String operator is easier to combine a String statement with a list data.
Example:
>>> tup = (1,2,3)
>>> print "First: %d, Second: %d, Third: %d" % tup
First: 1, Second: 2, Third: 3
However, using the .format() function, you will end up with a verbose statement.
Example:
>>> tup = (1,2,3)
>>> print "First: %d, Second: %d, Third: %d" % tup
>>> print 'First: {}, Second: {}, Third: {}'.format(1,2,3)
>>> print 'First: {0[0]}, Second: {0[1]}, Third: {0[2]}'.format(tup)
First: 1, Second: 2, Third: 3
First: 1, Second: 2, Third: 3
First: 1, Second: 2, Third: 3
Further more, '%' string operator also useful for us to validate the data type such as %s, %d, %i, while .format() only support two conversion flags: '!s' and '!r'.
>>> tup = (1, 2, 3)
>>> print "Here it is: %s" % (tup,)
Here it is: (1, 2, 3)
>>>
Note that (tup,) is a tuple containing a tuple. The outer tuple is the argument to the % operator. The inner tuple is its content, which is actually printed.
(tup) is an expression in brackets, which when evaluated results in tup.
(tup,) with the trailing comma is a tuple, which contains tup as is only member.
Even though this question is quite old and has many different answers, I'd still like to add the imho most "pythonic" and also readable/concise answer.
Since the general tuple printing method is already shown correctly by Antimony, this is an addition for printing each element in a tuple separately, as Fong Kah Chun has shown correctly with the %s syntax.
Interestingly it has been only mentioned in a comment, but using an asterisk operator to unpack the tuple yields full flexibility and readability using the str.format method when printing tuple elements separately.
tup = (1, 2, 3)
print('Element(s) of the tuple: One {0}, two {1}, three {2}'.format(*tup))
This also avoids printing a trailing comma when printing a single-element tuple, as circumvented by Jacob CUI with replace. (Even though imho the trailing comma representation is correct if wanting to preserve the type representation when printing):
tup = (1, )
print('Element(s) of the tuple: One {0}'.format(*tup))
This doesn't use string formatting, but you should be able to do:
print 'this is a tuple ', (1, 2, 3)
If you really want to use string formatting:
print 'this is a tuple %s' % str((1, 2, 3))
# or
print 'this is a tuple %s' % ((1, 2, 3),)
Note, this assumes you are using a Python version earlier than 3.0.
t = (1, 2, 3)
# the comma (,) concatenates the strings and adds a space
print "this is a tuple", (t)
# format is the most flexible way to do string formatting
print "this is a tuple {0}".format(t)
# classic string formatting
# I use it only when working with older Python versions
print "this is a tuple %s" % repr(t)
print "this is a tuple %s" % str(t)
Besides the methods proposed in the other answers, since Python 3.6 you can also use Literal String Interpolation (f-strings):
>>> tup = (1,2,3)
>>> print(f'this is a tuple {tup}')
this is a tuple (1, 2, 3)
I think the best way to do this is:
t = (1,2,3)
print "This is a tuple: %s" % str(t)
If you're familiar with printf style formatting, then Python supports its own version. In Python, this is done using the "%" operator applied to strings (an overload of the modulo operator), which takes any string and applies printf-style formatting to it.
In our case, we are telling it to print "This is a tuple: ", and then adding a string "%s", and for the actual string, we're passing in a string representation of the tuple (by calling str(t)).
If you're not familiar with printf style formatting, I highly suggest learning, since it's very standard. Most languages support it in one way or another.
Please note a trailing comma will be added if the tuple only has one item. e.g:
t = (1,)
print 'this is a tuple {}'.format(t)
and you'll get:
'this is a tuple (1,)'
in some cases e.g. you want to get a quoted list to be used in mysql query string like
SELECT name FROM students WHERE name IN ('Tom', 'Jerry');
you need to consider to remove the tailing comma use replace(',)', ')') after formatting because it's possible that the tuple has only 1 item like ('Tom',), so the tailing comma needs to be removed:
query_string = 'SELECT name FROM students WHERE name IN {}'.format(t).replace(',)', ')')
Please suggest if you have decent way of removing this comma in the output.
For python 3
tup = (1,2,3)
print("this is a tuple %s" % str(tup))
Try this to get an answer:
>>>d = ('1', '2')
>>> print("Value: %s" %(d))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: not all arguments converted during string formatting
If we put only-one tuple inside (), it makes a tuple itself:
>>> (d)
('1', '2')
This means the above print statement will look like:
print("Value: %s" %('1', '2')) which is an error!
Hence:
>>> (d,)
(('1', '2'),)
>>>
Above will be fed correctly to the print's arguments.
You can try this one as well;
tup = (1,2,3)
print("this is a tuple {something}".format(something=tup))
You can't use %something with (tup) just because of packing and unpacking concept with tuple.
Using f-string for a quick print in python3.
tup = (1,2,3)
print(f"this is a tuple {tup}")
how much changed over the years. Now you can do this:
tup = (1,2,3)
print(f'This is a Tuple {tup}.')
Results in: This is a Tuple (1,2,3).
Talk is cheap, show you the code:
>>> tup = (10, 20, 30)
>>> i = 50
>>> print '%d %s'%(i,tup)
50 (10, 20, 30)
>>> print '%s'%(tup,)
(10, 20, 30)
>>>

Categories