给字符串添加换行符,跨平台

Add newline to string, cross-platform

我正在我的应用程序中生成一些文本。由于文本是更大消息的一部分,有时我需要添加换行符,有时不需要:

NEWLINE = '\n'  # TODO: how to define this cross-platform? Can I use os.linesep?

def get_txt(add_newline=False):
    txt = 'Hello'
    if add_newline:
        txt += NEWLINE
    return txt

可以这样使用:

def get_message():
    msg = get_txt(True)
    msg += get_txt(True)
    msg += get_txt(False)
    return msg

哪个 return:

Hello
Hello
Hello (no newline here)

如何以跨平台的方式定义 NEWLINE?或者更好的是,标准库中是否有一个函数(或包含在 python 中)可以将换行符附加到字符串? (打印时不一定,只需要在内存中的字符串后面追加一个换行符即可)。使用的换行符应该是适合平台的换行符 python 是 运行

我一直只使用换行符 '\n' 来表示换行符,尽管 windows 使用换行符和回车 return 字符,我在 [=16] 上进行了测试=] machine (python 3.4) 在内存中构建一个字符串然后将其写入文件,而在内存中它保持为单个字符 ('\n') 但是当写入文件时它被转换为两个字符使正确的行结束于 windows.
到目前为止,我还没有遇到过有这个问题的图书馆。

你可以试试这个:

import os
print(os.linesep)

Python 使用 \n 表示换行符。

Python 会根据平台自动将 \n 转换为正确的换行符。

你也可以试试

import os
print (os.linesep)

您需要打印您的消息以使其显示为新行。

get_txt()
msg = get_message()
print(msg)

会给你:

Hello
Hello
Hello

只需要确保打印到文件即可。