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
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.
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.
By using: \n – It prints new line. By using: \x0A or \xA (ASCII literal of \n) – It prints new line.
The new line character in Python is \n . It is used to indicate the end of a line of text.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With