How to write the original multi-line string in Python?

  • I know that you can create a multi-line string in several ways:

Triple quotes

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

concatenation

 ('this is ' 'a string') 

Shielding

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

     r'C:\Path\To\File' 

However, I have a long path to a file that spans several lines and should be unprocessed. How to do it?

It works:

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

But for some reason this is not the case:

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

Why does "t" only have a backslash?

+2
source share
2 answers

For each string literal, you need the r prefix

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

Otherwise, the first part is interpreted as a string literal, but the next line of the string is missing, therefore '\t ' is interpreted as a tab character.

+2
source

I think you might also need to make the second line an unprocessed line by first adding it to r, as you did in r'on\e'

0
source

All Articles