Search code examples
pythoncode-formattingrawstring

Linebreak a raw string


I'm looking for a good way to linebreak long raw strings in python. The reason for that is, that I'm often using windows path together with pathlibs Path, as this allows me for convenient copy pasting on both windows and *nix like this:

from pathlib import Path
my_long_path = Path(r'C:some\very\long\path')

Now naturally, filepaths can get quite long and for better code formatting I sometimes want to linebreak raw strings.

What doesn't work is tripple quotes, because of the linebreak symbol:

a = r'''some\
very\long\path'''

--> 'some\\\nvery\long\path'

So the only option I know is:

a = r'some\'\
r'very\long\path'

It works but feels a little un-pythonic. Is there a better way to do this?


Solution

  • You can use brackets: This is also found here How to write very long string that conforms with PEP8 and prevent E501

    s = ("this is my really, really, really, really, really, really, " # comments ok
         "really long string that I'd like to shorten.")
    
    print(s)
    >>>> this is my really, really, really, really, really, really, really long string that I'd like to shorten.