11
  1. I know that you can create a multi-line string a few ways:

Triple Quotes

'''
This is a 
multi-line
string.
'''

Concatenating

('this is '
'a string')

Escaping

'This is'\
'a string'
  1. I also know that prefixing the string with r will make it a raw string, useful for filepaths.

    r'C:\Path\To\File'
    

However, I have a long filepath that both spans multiple lines and needs to be a raw string. How do I do this?

This works:

In [1]: (r'a\b'
   ...: '\c\d')
Out[1]: 'a\\b\\c\\d'

But for some reason, this doesn't:

In [4]:  (r'on\e'
   ...: '\tw\o')
Out[4]: 'on\\e\tw\\o'

Why does the "t" only have one backslash?

3
  • 7
    r'''...''' works just fine to make a raw multiline string. Sep 1, 2017 at 15:43
  • 3
    @jasonharper No it doesn't, it adds the \n for new line: In [7]: r'''path\to ...: \file''' Out[7]: 'path\\to\n\\file'
    – Josh D
    Sep 1, 2017 at 16:21
  • 1
    The triple quotes are used to create a multi-line string (string that contains newlines). Concatenating and escaping are used to create a multi-line code representation of a single-line string.
    – Jeyekomon
    Jul 9, 2021 at 13:13

2 Answers 2

16

You'd need a r prefix on each string literal

>>> (r'on\e'
     r'\tw\o')
'on\\e\\tw\\o'

Otherwise the first portion is interpreted as a raw string literal, but the next line of string is not, so the '\t' is interpreted as a tab character.

2
  • 1
    That's a pain in the neck for long filepaths. Any other ideas for raw multiline strings?
    – Josh D
    Sep 1, 2017 at 15:29
  • @JoshD This is one of the preferred solutions for all strings (not just the raw ones) that need to be split over multiple lines.
    – Jeyekomon
    Jul 9, 2021 at 13:03
0

I think you might also need to make the second line a raw string as well by prefixing it with the r as you did in r'on\e'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.