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)
>>>
Related
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)'
How can I create a tuple consisting of just an empty tuple, i.e. (())? I have tried tuple(tuple()), tuple(tuple(tuple())), tuple([]) and tuple(tuple([])) which all gave me ().
The reason that I use such a thing is as follows: Assume you have n bags with m items. To represent a list of items in a bag, I use a tuple of length n where each element of that tuple is a representative for a bag. A bag might be empty, which is labeled by (). Now, at some initial point, I have just one bag with empty items!
The empty tuple is () (or the more-verbose and slower tuple()), and a tuple with just one item (such as the integer 1), called a singleton (see here and here) is (1,). Therefore, the tuple containing only the empty tuple is
((),)
Here are some results showing that works:
>>> a=((),)
>>> type(a)
<type 'tuple'>
>>> len(a)
1
>>> a[0]
()
>>> type(a[0])
<type 'tuple'>
>>> len(a[0])
0
I'm not surprised this (()) didn't work, since the outer parentheses get interpreted as that - parentheses. So (()) == (), just like (2) == 2. This should work, however:
((),)
An empty tuple:
my_tuple = ()
A tuple with 1 string:
my_tuple = ('foo',)
A tuple with 2 strings:
my_tuple = ('foo', 'bar')
A tuple with 1 empty tuple:
my_tuple = ((),)
A tuple with 2 empty tuples:
my_tuple = ((), ())
in Python 2, tuple() is the only genuine empty tuple, but (), and ((),) create a tuple of length 1 that contains a tuple of length 0 - but not a tuple of length zero itself.
If you want an answer to "how do I create an empty (or zero length) tuple.... I found this post with the search "how to create an empty tuple", then realized this was not the same question, but could be mistaken for that question (as the search does), so I though I would provide the answer to :
How do you simply create an empty tuple?
the original question could mislead you, as the original answers are almost good enough as an empty tuple, but do fail one test.
(), will create an 'empty' tuple as suggested in previous answers with ((),) which will also work, as will ((( ((( (),))) ))) in fact you can use any number of outer brackets you choose, they just work as brackets. However, python, when printing a tuple, does add one set of outer brackets.
empty brackets is a non-standard representation of 'no value' and adding the trailing comma makes a tuple from 'no value'. But it is a tuple with a 'no value' entry, not an empty tuple.
Note: This is not a zero length tuple, as the other examples have also shown. The outer tuple is a tuple with one value, just that value has itself, is the empty tuple. So this creates an empty tuple inside another tuple, and the other tuple is not empty. For a true empty tuple by itself, use tuple() although the (), behaves some what similar, it is not quite correct.
>>> a = (),
>>> type(a)
<class 'tuple'>
>>> len(a)
1
>>> a
((),)
>>> len(a[0]) # the inside tuple is empty, just not the outside one
0
Similarly, for a tuple of length 1 but with a value (of zero in the case of b, and "" for the example with c)
>>> b = 0,
>>> type(b)
<class 'tuple'>
>>> len(b)
1
>>>b
(0,)
# now with an empty string
>>> c = "",
>>> type(c)
<class 'tuple'>
>>> len(c)
1
>>>c
('',)
>>> len (c[0]) # same len of c[0] as with 'empty' tuple
0
So the outer brackets are included for displaying a tuple, but not actually part of the tuple, nor needed for creating the tuple.
However all these brackets methods are not a real empty at the outer level, which is something that also has use cases.
>>> a = ((),) # extra brackets just to show same as other answers
>>> len(a)
1
>>> if a:
print("not empty")
not empty
>>> e = tuple()
>>> len(e)
0
>>> type(e)
<class 'tuple'>
>>> if e:
print("not empty")
>>> # note...did not print...so e acts as false as an empty tuple should
So if you really need a genuine empty tuple, use tuple(), but if near enough is all you need, you can use (), or ((),)
In the general case, it's the commas that make tuples, not the parentheses. Things become confusing in the case of empty tuples because a standalone comma is syntactically incorrect. So for the special case of an empty tuple, the "it is commas that make tuples" rule does not apply, and the special case () syntax is used instead.
I have a format string that I am creating dynamically based on user input. I am collecting the arguments for the format string in a list, and I'd like to know how to unpack them at the end of the format string. I've seen some questions that seem related to this, but I'm very new to Python and I can't seem to apply their solutions to my case.
The idea of what I'd like to do is:
my_string = "string contents" % tuple([for item in var_array])
Of course this isn't valid syntax but hopefully it describes what I am trying to do: I'd like to unpack var_array as my list of arguments without knowing the length of var_array ahead of time. How could I do this?
Edit:
I'll attempt to better explain my problem. I'm creating a format string by concatenating an unknown number of format strings. Thus my final string will have a a variable number of %s and therefore a variable number of args that are collected in a list.
For example:
"My format string might have %s or %s arguments" %([arg_list]) //here arg_list has 2 arguments
"But my format string might also have %s or %s or %s arguments. %([arg_list]) //here arg_list has 3 arguments
The length of the format string, and the number of arguments are variable based on user input so I want to be able to tack on a list of args at the end of the final string. Is this possible?
Here is an approach that goes from arguments to a formatted string (error checking is still needed):
>>> def StartDance(*args):
return "%d, %d, %d, %d!" % tuple(args)
>>> StartDance(5, 6, 7, 8)
'5, 6, 7, 8!'
Here is a more robust solution to error checking but I'm presenting it as a separate answer considering how much extra complexity it is adding:
>>> def StartDance(*args):
return (", ".join(["%d"] * len(args))+"!") % tuple(args)
>>> StartDance(5, 6, 7, 8)
'5, 6, 7, 8!'
>>> StartDance(5, 6, 7, 8, 9, 10)
'5, 6, 7, 8, 9, 10!'
>>> StartDance(1)
'1!'
And here is a function returning a list which is being unpacked as arguments only to have these arguments treated as a list (Python is fun :)
>>> StartDance(*range(5,9))
'5, 6, 7, 8!'
Assuming what you want to make into a string supports the str builtin, you can do:
def join_args(*args):
return " ".join([str(x) for x in args])
print(join_args(1,2,3,4,5,6))
print(join_args('1','2','3','4'))
Out:
1 2 3 4 5 6
1 2 3 4
You could also use the following for a more flexible string:
def join_args(fmstr, *args):
return fmstr.format(*args)
print(join_args("One: {} Two: {} Three: {} Four: {}", 1,2,3,4))
Out:
One: 1 Two: 2 Three: 3 Four: 4
Just make sure there are an equal number of args and {}.
You're very close, try something like this:
"%s my %s is %s" % tuple(["Hi", "name", "butch"])
I got my results from sqlite by python, it's like this kind of tuples: (u'PR:000017512',)
However, I wanna print it as 'PR:000017512'. At first, I tried to select the first one in tuple by using index [0]. But the print out results is still u'PR:000017512'. Then I used str() to convert and nothing changed. How can I print this without u''?
You're confusing the string representation with its value. When you print a unicode string the u doesn't get printed:
>>> foo=u'abc'
>>> foo
u'abc'
>>> print foo
abc
Update:
Since you're dealing with a tuple, you don't get off this easy: You have to print the members of the tuple:
>>> foo=(u'abc',)
>>> print foo
(u'abc',)
>>> # If the tuple really only has one member, you can just subscript it:
>>> print foo[0]
abc
>>> # Join is a more realistic approach when dealing with iterables:
>>> print '\n'.join(foo)
abc
Don't see the problem:
>>> x = (u'PR:000017512',)
>>> print x
(u'PR:000017512',)
>>> print x[0]
PR:000017512
>>>
You the string is in unicode format, but it still means PR:000017512
Check out the docs on String literals
http://docs.python.org/2/reference/lexical_analysis.html#string-literals
In [22]: unicode('foo').encode('ascii','replace')
Out[22]: 'foo'
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.