Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 826
blueFast Avatar asked Feb 26 '16 14:02

blueFast


People also ask

Can you put \n in a string?

In Windows, a new line is denoted using “\r\n”, sometimes called a Carriage Return and Line Feed, or CRLF. Adding a new line in Java is as simple as including “\n” , “\r”, or “\r\n” at the end of our string.

How do you add a new line to a string in Python?

In Python, the new line character “\n” is used to create a new line. When inserted in a string all the characters after the character are added to a new line. Essentially the occurrence of the “\n” indicates that the line ends here and the remaining characters would be displayed in a new line.

Does \n work in C#?

By using: \n – It prints new line. By using: \x0A or \xA (ASCII literal of \n) – It prints new line.

Can we use \n in Python?

The new line character in Python is \n . It is used to indicate the end of a line of text.


2 Answers

You can try with this:

import os
print(os.linesep)
like image 197
decadenza Avatar answered Oct 06 '22 04:10

decadenza


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.

like image 40
James Kent Avatar answered Oct 06 '22 05:10

James Kent