How to correctly write a raw multiline string in Python?

怎甘沉沦 提交于 2019-12-29 08:02:20

问题


  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?


回答1:


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:


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'



来源:https://stackoverflow.com/questions/46003452/how-to-correctly-write-a-raw-multiline-string-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!