2

嗨,我想将换行符写入输出文件,所以这是我的代码:

a=['\n:001000', '\r:10111', ' :000', '!:01101111101', '":0010011', "':0010010110", '(:00100101111110110', '):00100101111110111', ',:101100', '-:1011011011', '.:0100100', '0:011011111001101', '1:0110111110010', '2:1011011000111', '3:011011111001110']

text_file = open("Output.txt", "wb")
    for t in a:
        text_file.write(t+" ")

但我的输出不是我所期望的:

:001000  :10111   :000  !:01101111101  ":0010011  ':0010010110  (:00100101111110110  ):00100101111110111  ,:101100  -:1011011011  .:0100100  0:011011111001101  1:0110111110010  2:1011011000111  3:011011111001110  

有谁知道如何将换行符实际写入输出???

我想要类似的东西: \n:001000 \r:10111 等

4

2 回答 2

1

您正在打印这些字符,只需查看repr

>>> a=['\n:001000 ', '\r:10111 ', ' :000 ', '!:01101111101 ', '":0010011 ', "':0010010110 ", '(:00100101111110110 ', '):00100101111110111 ', ',:101100 ', '-:1011011011 ', '.:0100100 ', '0:011011111001101 ', '1:0110111110010 ', '2:1011011000111 ', '3:011011111001110 ']
>>> with open("Output.txt", "wb") as f:
        for t in a:
            f.write(t + " ")


>>> with open("Output.txt", "rb") as f:
        print repr(f.read()) # representation


'\n:001000  \r:10111   :000  !:01101111101  ":0010011  \':0010010110  (:00100101111110110  ):00100101111110111  ,:101100  -:1011011011  .:0100100  0:011011111001101  1:0110111110010  2:1011011000111  3:011011111001110  '

或者,也许您要求转义这些字符以原始打印它们:

>>> with open("Output.txt", "wb") as f:
        for t in a:
            f.write((t + " ").encode('string_escape'))


>>> with open("Output.txt", "rb") as f:
        print f.read()


\n:001000  \r:10111   :000  !:01101111101  ":0010011  \':0010010110  (:00100101111110110  ):00100101111110111  ,:101100  -:1011011011  .:0100100  0:011011111001101  1:0110111110010  2:1011011000111  3:011011111001110  
于 2013-05-01T08:26:22.993 回答
0

换行符是 '\n'

于 2013-05-01T08:21:34.550 回答