Python:创建元组时字符串被转义 [英] Python: string is escaped when creating a tuple

查看:37
本文介绍了Python:创建元组时字符串被转义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

string = "ad\23e\4x{\s"数据 =(字符串,)

当我打印数据时,元组中的字符串对于每个斜杠都有一个额外的斜杠,总共有 6 个反斜杠.

如何避免额外的反斜杠?

解决方案

对象 data 是一个元组.当你打印一个元组时,Python 会为每个元素调用 repr.如果您想以其他方式对其进行格式化,则必须自己进行转换.

<预><代码>>>>s = "广告\23e\4x{\s">>>d = (s,)>>>打印('ad\x13e\x04{\\s',)>>>打印 '(%s,)' % (', '.join('"%s"' % _ for _ in d))("adex{\s")

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

这篇关于Python:创建元组时字符串被转义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆