【问题标题】:Python: single backslash automatically replaced by double backslash when printing a list [duplicate]Python:打印列表时单反斜杠自动替换为双反斜杠[重复]
【发布时间】:2022-08-07 11:48:42
【问题描述】:
我有一个包含单个反斜杠的字符串数组/列表。
stringArray = [\'this \\\\ is\', \'a \\\\ sample\', \'backslash \\\\ text\']
当我在控制台中单独打印它们时,它们会完全按照预期显示(考虑到要编写单个反斜杠,您需要键入两个反斜杠):
print(stringArray[0])
print(stringArray[2])
输出:
this \\ is
backslash \\ text
但是每当我打印数组的一个或多个元素时,就会出现双反斜杠:
print(stringArray)
输出:
[\'this \\\\ is\', \'a \\\\ sample\', \'backslash \\\\ text\']
我尝试了几种方法来生成数组,它们总是有相同的结果。即使在字符串中写入一个反斜杠,结果也完全相同。
为什么会发生这种情况,如何获得带有单个反斜杠的字符串列表?
标签:
python
list
backslash
【解决方案1】:
在直接打印字符串和显示该字符串的表示之间存在。
一个简单的例子是:
>>> '\\'
'\\'
>>> print('\\')
\
你可以一个有引号和两个反斜杠(代表一个反斜杠)。当您打印一个列表时,您将显示包含的所有字符串的表示。
这是如何运作的?
当您调用print() 时,python 首先尝试调用对象上的__str__ 方法(如果该对象不存在),它会调用__repr__ 以进行“调试”表示。
Here's 更多解释,但简而言之,__str__ 是可读的,__repr__ 是明确表示对象。
【解决方案2】:
正如this answer 中提到的,在列表上调用__str__()(这是print() 所做的),在其中的项目上调用__repr__()。这就是为什么你得到'this \\ is' 而不是this \ is。
解决方案是使用join() 并自己构造字符串,如下所示:
print(f'[{", ".join(stringArray)}]')
这导致输出:
[this \ is, a \ sample, backslash \ text]