How to correctly write a raw multiline string in Python?
Asked Answered
W

2

13
  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?

Waylon answered 1/9, 2017 at 15:23 Comment(3)
r'''...''' works just fine to make a raw multiline string.Harker
@Harker No it doesn't, it adds the \n for new line: In [7]: r'''path\to ...: \file''' Out[7]: 'path\\to\n\\file'Waylon
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.Hurrah
B
18

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.

Banna answered 1/9, 2017 at 15:27 Comment(2)
That's a pain in the neck for long filepaths. Any other ideas for raw multiline strings?Waylon
@JoshD This is one of the preferred solutions for all strings (not just the raw ones) that need to be split over multiple lines.Hurrah
J
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'

Juggle answered 1/9, 2017 at 15:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.