Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

336
Views
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

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

You can try with this:

import os
print(os.linesep)
over 4 years ago · Santiago Trujillo Report

0

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.

over 4 years ago · Santiago Trujillo Report

0

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)
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!