Python: string is escaped when creating a tuple [duplicate]
I have the following code:
string = "ad开发者_运维问答\23e\4x{\s"
data = (string,)
When I print the data my string in the tuple has an extra slash for each slash a total of 6 back slashes.
How can I avoid the extra back slashes?
The object data
is a tuple. When you print a tuple, Python call repr
for each element. If you want to format it another way, you have to do the conversion yourself.
>>> s = "ad\23e\4x{\s"
>>> d = (s,)
>>> print d
('ad\x13e\x04{\\s',)
>>> print '(%s,)' % (', '.join('"%s"' % _ for _ in d))
("adex{\s")
Those extra backslashes aren't actually in your string, they are just how Python represents strings (the idea being that you could paste that back into a program and it would work). It's doing that because the tuple's __str__()
implementation calls repr()
on each item. If you print string
or print data[0]
you will see what's actually in the string.
You mean something like this?
In [11]: string = r'ad\23e\4x{\s'
In [12]: string
Out[12]: 'ad\\23e\\4x{\\s'
In [13]: print string
ad\23e\4x{\s
In [14]: data=(string,)
In [15]: data
Out[15]: ('ad\\23e\\4x{\\s',)
In [16]: print data
('ad\\23e\\4x{\\s',)
In [17]: print data[0]
ad\23e\4x{\s
精彩评论