Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly write a raw multiline string in Python?

  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?

like image 986
Josh D Avatar asked Sep 01 '17 15:09

Josh D


People also ask

How do you declare a raw string in Python?

Python raw string is created by prefixing a string literal with 'r' or 'R'. Python raw string treats backslash (\) as a literal character. This is useful when we want to have a string that contains backslash and don't want it to be treated as an escape character.

What is a multiline string in Python?

A multiline string in Python begins and ends with either three single quotes or three double quotes. Any quotes, tabs, or newlines in between the “triple quotes” are considered part of the string. Python's indentation rules for blocks do not apply to lines inside a multiline string.


1 Answers

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.

like image 135
Cory Kramer Avatar answered Oct 21 '22 15:10

Cory Kramer