换行符或“\ n”不起作用。

问题描述:

你能告诉我为什么换行符\ n不工作吗?换行符或“ n”不起作用。

itemsToWriteToFile = "Number 1:", 12, "\nNumber 2: ", 13, "\nNumber 3: ", 13, "\nNumber 4: ", 14 
itemsToWriteToFile = str(itemsToWriteToFile) 

itemsToWriteToFile = itemsToWriteToFile.replace('(', "") 
itemsToWriteToFile = itemsToWriteToFile.replace(')', "") 
itemsToWriteToFile = itemsToWriteToFile.replace('"', "") 
itemsToWriteToFile = itemsToWriteToFile.replace(',', "") 
itemsToWriteToFile = itemsToWriteToFile.replace('\n', "") 

print(itemsToWriteToFile) 
+0

你为什么要摆在首位字符串和整数的元组转换为字符串?你的目标是什么? – DSM

+0

哦,对不起...完全看到这个出现在JS标签。 (删除原始评论)。 –

+0

DSM,代码从我原来的程序中稍微修改,所以它更有意义。 –

str()转换将“\ n”转换为“\\ n”。

>>> str('\n') 
'\n' 
>>> str(['\n']) 
"['\\n']" 

这是怎么回事?当您在列表上调用str()(对于元组而言)时,将调用该列表的__str__()方法,该方法依次在其每个元素上调用__repr__()。让我们来看看它的行为:

>>> "\n".__str__() 
'\n' 
>>> "\n".__repr__() 
"'\\n'" 

所以你有这个原因。

至于如何解决它,就像搅拌机建议,最好的办法是在名单上没有使用str()

''.join(str(x) for x in itemsToWriteToFile) 
+0

为什么在使用str()时添加第二个“\”? –

+0

我已更新我的答案。至于str .__ repr__的行为,我找不到解释它的任何引用,但它有意义,因为您希望可视化字符串的内容,而不是实际的字符串。 –

+0

这是不正确的。你不应该首先替换它们。 – Blender

使用itemsToWriteToFile.replace('\\n', "")而不是itemsToWriteToFile.replace('\n', "")

>>itemsToWriteToFile = itemsToWriteToFile.replace('\\n', "") 

Final Output:- 

>>> print(itemsToWriteToFile) 
'Number 1:' 12 'Number 2: ' 13 'Number 3: ' 13 'Number 4: ' 14 

使用本

itemsToWriteToFile = itemsToWriteToFile.translate(None, "(),\"\\n") 

所有其他答案正在修复一个问题,即sh甚至不存在。将你的字符串和整数元组转换成一串字符串。然后,使用str.join()加入他们一起放入一个大的字符串:

foo = "Number 1:", 12, "\nNumber 2: ", 13, "\nNumber 3: ", 13, "\nNumber 4: ", 14 
bar = map(str, foo) 

print(''.join(bar)) 
+0

我明白你在那里做了什么。感谢您的建议。 –

+0

这个答案很好,但我不会说它比齐格弗里德更好。我GOOGLE了“python换行不工作”,并得到了这个问题。 OP代码的优化对我来说毫无意义,我怀疑大多数人。知道'str('\ n')'返回''\ n''是非常有用的。 – gwg

+0

@gwg:这不是一个优化。如果你想一起加入,可以使用'str.join()'。 (Ab)使用'str(itemsToWriteToFile)',然后删除括号,逗号和引号就是错误的方法。这就像使用'eval(str(a)+'*'+ str(b))'来乘以两个数字。 – Blender