delavnog delavnog -4 years ago 174
Linux Question

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download