如何在Python中正确编写原始多行字符串? [英] How to correctly write a raw multiline string in Python?

查看:93
本文介绍了如何在Python中正确编写原始多行字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  1. 我知道您可以通过以下几种方式创建多行字符串:

三引号

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

串联

('this is '
'a string')

转义

'This is'\
'a string'

  1. 我还知道,在字符串前面加上r将使它成为原始字符串,对于文件路径很有用.

  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?

这有效:

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'

为什么"t"只有一个反斜杠?

Why does the "t" only have one backslash?

推荐答案

每个字符串文字上都需要一个r前缀

You'd need a r prefix on each string literal

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

否则,第一部分将被解释为原始字符串文字,但字符串的下一行则不会,因此'\t'被解释为制表符.

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.

这篇关于如何在Python中正确编写原始多行字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆