Python: string is escaped when creating a tuple

被刻印的时光 ゝ 提交于 2019-12-13 19:09:13

问题


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?


回答1:


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



回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/7145934/python-string-is-escaped-when-creating-a-tuple

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!