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

时间:2022-02-10 12:21:34

I am generating some text in my application. Since the text is part of a bigger message, sometimes I need to add newlines, sometimes not:

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

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

This could be used as follows:

这可以使用如下:

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

Which would return:

哪会回来:

Hello
Hello
Hello (no newline here)

How can I define NEWLINE in a cross-platform manner? Or better yet, is there a function in the standard library (or included in python) which can append a newline to a string? (not necessarily when printing, just append a newline to the string in memory). The newline used should be the right one for the platform were python is running

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

2 个解决方案

#1


4  

I've always just used the newline character '\n' to signify a linebreak, although windows uses a newline and a carriage return character, I tested on my windows machine (python 3.4) building a string in memory and then writing it to file, while in memory it stays as a single character ('\n') however when written to file it gets converted into two characters to have the correct line ending on windows.
up till now I have yet to come across a single library that had an issue with this.

我总是只使用换行符'\ n'来表示换行符,虽然windows使用换行符和回车符,我在我的windows机器上测试(python 3.4)在内存中构建一个字符串然后将其写入文件,在内存中它保持为单个字符('\ n'),但是当写入文件时,它会转换为两个字符,以便在Windows上以正确的行结束。到目前为止,我还没有遇到过一个有问题的图书馆。

#2


5  

You can try with this:

你可以尝试这个:

import os
print(os.linesep)

#1


4  

I've always just used the newline character '\n' to signify a linebreak, although windows uses a newline and a carriage return character, I tested on my windows machine (python 3.4) building a string in memory and then writing it to file, while in memory it stays as a single character ('\n') however when written to file it gets converted into two characters to have the correct line ending on windows.
up till now I have yet to come across a single library that had an issue with this.

我总是只使用换行符'\ n'来表示换行符,虽然windows使用换行符和回车符,我在我的windows机器上测试(python 3.4)在内存中构建一个字符串然后将其写入文件,在内存中它保持为单个字符('\ n'),但是当写入文件时,它会转换为两个字符,以便在Windows上以正确的行结束。到目前为止,我还没有遇到过一个有问题的图书馆。

#2


5  

You can try with this:

你可以尝试这个:

import os
print(os.linesep)