I have a function and returning three values, The return value for my function is
(1, 3, "<class 'int'>")
while I want to return
(1, 3, <class 'int'>)
How do I remove the quotes from my return value.str(type(element)) is the value which is returning the 3rd value
def is_list_permutation(L1, L2):
L1set = set(L1)
L2set = set(L2)
count = 0
element = ''
if L1 == [] and L2 == []:
return(None,None,None)
elif len(L1) == len(L2) and L1set == L2set:
for a in L1:
if L1.count(a) == L2.count(a):
if L1.count(a) > count:
count = L1.count(a)
element = a
return(element,count,str(type(element)))
else:
return False
break
else:
return False
so if i give
L1 = [1, 'b', 1, 'c', 'c', 1]
L2 = ['c', 1, 'b', 1, 1, 'c']
then the result is (1, 3, "<class 'int'>") while I want (1, 3, <class 'int'>)
Your function is returning a tuple with three elements: element, count and the string representation of the type of element. At no point, this has any string representation which you’re seeing there. You just get back a tuple.
Now, when you print that tuple, then the print function will actually try to convert it into a string. For a tuple, this string representation is defined to be a set of parentheses (), and the repr() string representation of each tuple element inside.
For numbers, this will look fine since repr(5) happens to be the string '5'. But for strings, the repr will add quotes to make sure that the return string would be valid Python code:
>>> repr('foo')
"'foo'"
>>> print(repr('foo'))
'foo'
Now, when you say, you want the result without those quotes, you have to think about what that actually means. You could easily format the result string yourself. For example like this:
return '({0}, {1}, {2})'.format(element, count, str(type(element)))
This will return a string that would look like the way you want.
However, by doing that, you also lose the information you had when you returned a tuple. Now, you just return a string that has no information about the actual source values. So you cannot take the count value out without parsing the string again.
So, think about what you want to do: Do you actually just want something nice to print, or do you actually want to get those three values individually as a return value to be able to use them for something else afterwards?
You could always consider printing the text in the desired format later, if you already have the return values as a tuple…
Btw.: Note that when not calling str(type(element)) but just type(element), you would get back a type element (instead of a string). And the repr() of a type element happens to be exactly what you would want to have. So as a quick fix, you could always get rid of that str() call there.
There will always be some quotes around it because it is a string!
If you want to return None when the string is "" then you could do this:
x = str(type(s))
return(element, count, x if x else None)
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')
Let's say I have a string
str1 = "TN 81 NZ 0025"
two = first2(str1)
print(two) # -> TN
How do I get the first two letters of this string? I need the first2 function for this.
It is as simple as string[:2]. A function can be easily written to do it, if you need.
Even this, is as simple as
def first2(s):
return s[:2]
In general, you can get the characters of a string from i until j with string[i:j].
string[:2] is shorthand for string[0:2]. This works for lists as well.
Learn about Python's slice notation at the official tutorial
t = "your string"
Play with the first N characters of a string with
def firstN(s, n=2):
return s[:n]
which is by default equivalent to
t[:2]
Heres what the simple function would look like:
def firstTwo(string):
return string[:2]
In python strings are list of characters, but they are not explicitly list type, just list-like (i.e. it can be treated like a list). More formally, they're known as sequence (see http://docs.python.org/2/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange):
>>> a = 'foo bar'
>>> isinstance(a, list)
False
>>> isinstance(a, str)
True
Since strings are sequence, you can use slicing to access parts of the list, denoted by list[start_index:end_index] see Explain Python's slice notation . For example:
>>> a = [1,2,3,4]
>>> a[0]
1 # first element, NOT a sequence.
>>> a[0:1]
[1] # a slice from first to second, a list, i.e. a sequence.
>>> a[0:2]
[1, 2]
>>> a[:2]
[1, 2]
>>> x = "foo bar"
>>> x[0:2]
'fo'
>>> x[:2]
'fo'
When undefined, the slice notation takes the starting position as the 0, and end position as len(sequence).
In the olden C days, it's an array of characters, the whole issue of dynamic vs static list sounds like legend now, see Python List vs. Array - when to use?
All previous examples will raise an exception in case your string is not long enough.
Another approach is to use
'yourstring'.ljust(100)[:100].strip().
This will give you first 100 chars.
You might get a shorter string in case your string last chars are spaces.
For completeness: Instead of using def you could give a name to a lambda function:
first2 = lambda s: s[:2]
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)
>>>