Issue
I am trying to do this code
vi = "--get"
x = "hello='"
cm = "'"
c = '='
v = '"'
w = "Hello, world"
num = raw_input()
hi = (vi+c+v+x+num+cm+v)
print (hi,w)
import pygtk
pygtk.require('2.0')
import gtk
clipboard = gtk.clipboard_get()
clipboard.set_text(str(vi+c+v+x+num+cm+v))
clipboard.store()
And when I print, it prints the number with this ' '.
How I can avoid this?
Solution
It's because in order to represent the tuple, (hi,w)
python needs to escape the interior single quotes. That's because python is choosing to enclose hi with single quotes because the first quote that it finds in hi
is a double quote.
You don't need to care about that though, because:
vi = "--get"
x = "hello='"
cm = "'"
c = '='
v = '"'
w = "Hello, world"
num = "23"
hi = (vi+c+v+x+num+cm+v)
print (hi,w)
print (hi,w)[0]
gives you:
('--get="hello=\'23\'"', 'Hello, world')
--get="hello='23'"
('--get="hello=\'23\'"', 'Hello, world')
is how python represents the tuple as a string. It doesn't mean that the first element of the tuple as the escape sequence in it. print (hi,w)[0]
gives you what you expected --get="hello='23'"
print '({},{})'.format(hi,w)
gives you:
(--get="hello='23'",Hello, world)
See this working example: https://paiza.io/projects/olg0_zf7G3SRsbXcGjSjXQ
The Point
(hi,w)
is an instance of the class tuple
. The reason why print (hi,w)
gives you ('--get="hello=\'23\'"', 'Hello, world')
is because that's what tuple.__str__()
is designed to do.
To illustrate the point, lets subclass tuple and override __str__()
to give the output you require.
class MyTuple(tuple):
def __str__(self):
return '({},{})'.format(*self)
foo = MyTuple((hi,w))
print foo
output:
(--get="hello='23'",Hello, world)
Overriding tuple is probably not a great idea but it works for this demonstration.
Answered By - shrewmouse
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.