简体   繁体   English

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

[英]Add newline to string, cross-platform

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?如何以跨平台的方式定义NEWLINE Or better yet, is there a function in the standard library (or included in python) which can append a newline to a string?或者更好的是,标准库中(或包含在 python 中)是否有一个函数可以将换行符附加到字符串? (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使用的换行符应该是 python 正在运行的平台的正确换行符

You can try with this:你可以试试这个:

import os
print(os.linesep)

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.我一直只使用换行符'\\n'来表示换行符,尽管 Windows 使用换行符和回车符,但我在我的 Windows 机器(python 3.4)上进行了测试,在内存中构建一个字符串,然后将其写入文件,而在内存中它保留为单个字符( '\\n' ),但是当写入文件时,它会转换为两个字符以在 Windows 上以正确的行结尾。
up till now I have yet to come across a single library that had an issue with this.到目前为止,我还没有遇到一个有这个问题的图书馆。

Python uses \\n to signify a line break. Python使用\\n来表示换行符。

Python automatically translates \\n to the proper newline character based on the platform. Python 会根据平台自动将\\n转换为正确的换行符。

You can also try你也可以试试

import os
print (os.linesep)

You need to print your message to have it displaying as new line.您需要打印消息以使其显示为新行。

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

will give you:会给你:

Hello
Hello
Hello

Just need make sure to print to file.只需要确保打印到文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM