gpt4 book ai didi

python - 转义单引号 (') in raw string r' ...'

转载 作者:太空狗 更新时间:2023-10-30 00:40:21 24 4
gpt4 key购买 nike

我要打印出来

this is '(single quote) and "(double quote)

我使用以下(我想在这里使用原始字符串'r')

a=r'this is \'(single quote) and "(double quote)' 

但是打印出来了

this is \'(single quote) and "(double quote)

在原始字符串中转义 ' 的正确方法是什么?

最佳答案

引自Python String Literals Docs ,

When an 'r' or 'R' prefix is present, a character following a backslash is included in the string without change, and all backslashes are left in the string. For example, the string literal r"\n" consists of two characters: a backslash and a lowercase 'n'. String quotes can be escaped with a backslash, but the backslash remains in the string; for example, r"\"" is a valid string literal consisting of two characters: a backslash and a double quote.

有两种方法可以解决这个问题

  1. 使用多行原始字符串,如 Python Strings 部分所述

    print(r"""this is '(single quote) and "(double quote)""")
    # this is '(single quote) and "(double quote)
  2. 使用 String literal concatenation ,

    print(r"this is '(single quote) and " r'"(double quote)')
    # this is '(single quote) and "(double quote)

关于python - 转义单引号 (') in raw string r' ...',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27467870/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com