为字符串添加换行符,跨平台 [英] Add newline to string, cross-platform

查看:35
本文介绍了为字符串添加换行符,跨平台的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这可以如下使用:

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

哪个会返回:

Hello
Hello
Hello (no newline here)

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

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

推荐答案

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

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.

这篇关于为字符串添加换行符,跨平台的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆