开发者

Python: string is escaped when creating a tuple [duplicate]

This question already has an answer here: Why does printing a tuple (list, dict, etc.) in Python double the backslashes? (1 answer) Closed 8 months ago.

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜