Question

I'm writing a python script that takes text from the clipboard using a pyqt QClipboard object.

The script parses the pasted text as a 2D list breaking into rows at line breaks.

I use windows and in most programming languages I'm used to checking of a '\n' character to identify a line break. The problem I'm hitting is that this script needs to work cross platform and it's not working right on a Mac and after doing some digging I've discovered that a Mac line ending is classed as '\r\n' in python

How can I identify the line endings consistently cross platform?

At the moment I have two separate areas that look for line endings

This one looks for a straggling EOL character and removes it:

if pastedtext[-1] == '\n':
    pastedtext = pastedtext[:-1]

While this splits the text at each EOL

pasted = pastedtext.split('\n')

This works fine on windows but not on mac. How can I get these lines to work correctly on both systems, or is there as way I can convert the pasted text into a specific platform's line ending style before running these lines?

Is my only option to branch into two separate handling procedures after doing a string search for '\r\n' in an 'if'?

Was it helpful?

Solution

This is what splitlines is for:

    lines = pastedtext.splitlines()

which will split the text into lines in a platform-independant way. The eol characters will be stripped from the lines, unless you pass True as an argument.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top