且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在原始 Python 字符串中包含引号

更新时间:2023-11-06 22:10:10

如果你想在字符串中使用双引号而不是单引号,你可以使用单引号作为分隔符:

r'what'ever'

如果您的字符串中需要两种引号,请使用三引号字符串:

r"""what"ever"""

如果你想在你的字符串中包含这两种三引号字符串(一种极不可能的情况),你不能这样做,你必须使用带有转义符的非原始字符串.

Consider:

>>> r"what"ever"
SyntaxError: invalid syntax
>>> r"what\"ever"
'what\\"ever'

So how do we get the quote, but not the slash?

And please don't suggest r'what"ever', because then the question just becomes how do we include both types of quotes?

Related

If you want to use double quotes in strings but not single quotes, you can just use single quotes as the delimiter instead:

r'what"ever'

If you need both kinds of quotes in your string, use a triple-quoted string:

r"""what"ev'er"""

If you want to include both kinds of triple-quoted strings in your string (an extremely unlikely case), you can't do it, and you'll have to use non-raw strings with escapes.