Mat*_*ide 5 python line-breaks
你能告诉我为什么断线\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)
Run Code Online (Sandbox Code Playgroud)
转换str()
是将“\n”转换为“\\n”。
>>> str('\n')
'\n'
>>> str(['\n'])
"['\\n']"
Run Code Online (Sandbox Code Playgroud)
那里发生了什么事?当您调用str()
列表(与元组相同)时,将调用__str__()
列表的方法,该方法又调用__repr__()
其每个元素。让我们检查一下它的行为是什么:
>>> "\n".__str__()
'\n'
>>> "\n".__repr__()
"'\\n'"
Run Code Online (Sandbox Code Playgroud)
所以这就是原因。
至于如何修复它,就像 Blender 提出的那样,最好的选择是不在str()
列表中使用:
''.join(str(x) for x in itemsToWriteToFile)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
16107 次 |
最近记录: |