如何用这个 "hello='23'" 代替这个 "hello=\'23\'"

How to get this "hello='23'" in place of this "hello=\'23\'"

我正在尝试执行此代码

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

当我打印时,用这个 \' \'

打印数字

如何避免这种情况

这是因为为了表示元组,(hi,w) python 需要转义内部单引号。这是因为 python 选择用单引号将 hi 括起来,因为它在 hi 中找到的第一个引号是双引号。

虽然你不需要关心这个,因为:

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]

给你:

('--get="hello=\'23\'"', 'Hello, world')
--get="hello='23'"

('--get="hello=\'23\'"', 'Hello, world') 是 python 将元组表示为字符串的方式。这并不意味着元组的第一个元素作为其中的转义序列。 print (hi,w)[0] 给你你所期望的 --get="hello='23'"

print '({},{})'.format(hi,w)

给你:

(--get="hello='23'",Hello, world)

查看这个工作示例:https://paiza.io/projects/olg0_zf7G3SRsbXcGjSjXQ

(hi,w) 是 class tuple 的实例。 print (hi,w) 给你 ('--get="hello=\'23\'"', 'Hello, world') 的原因是因为这就是 tuple.__str__() 的目的。

为了说明这一点,让 subclass 元组和覆盖 __str__() 来给出您需要的输出。

class MyTuple(tuple):

    def __str__(self):
        return '({},{})'.format(*self)

foo = MyTuple((hi,w))
print foo

输出:

(--get="hello='23'",Hello, world)

覆盖元组可能不是一个好主意,但它适用于此演示。