简体   繁体   中英

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? 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

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.
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 automatically translates \\n to the proper newline character based on the platform.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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