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?

smci
  • 32,567
  • 20
  • 113
  • 146
Josh D
  • 794
  • 4
  • 14
  • 31
  • 7
    `r'''...'''` works just fine to make a raw multiline string. – jasonharper Sep 01 '17 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 01 '17 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 09 '21 at 13:13

2 Answers2

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.

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • 1
    That's a pain in the neck for long filepaths. Any other ideas for raw multiline strings? – Josh D Sep 01 '17 at 15:29
  • @JoshD This is [one of the preferred solutions](https://stackoverflow.com/questions/10660435/pythonic-way-to-create-a-long-multi-line-string) for all strings (not just the raw ones) that need to be split over multiple lines. – Jeyekomon Jul 09 '21 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'

ddeamaral
  • 1,403
  • 2
  • 28
  • 43