【问题标题】:How can I replace \ in a specific string? [duplicate]如何替换特定字符串中的 \\? [复制]
【发布时间】:2022-08-07 14:16:24
【问题描述】:

我试图替换这个:\\ 在一个特定的字符串中:

\'\"Noir c\\\'est noir\", ont-ils dit, y a donc vraiment plus d\\\'espoir\'

但是当我使用.replace(\'\\\\\',\'\') 时,结果是:

\'\"Noir c\\\'est noir\", ont-ils dit, y a donc vraiment plus d\\\'espoir\'
  • 你不能同时使用双引号和单引号,使用双引号作为字符串
  • 在那儿实际上字符串中的斜线,或者它是你如何打印它的结果?如果你这样做print(your_string),它还会显示斜线吗?
  • 请包括定义字符串的代码和/或打印结果(连同打印它的代码)。如果我将您的字符串按原样复制并粘贴到 Python 解释器中,则它不包含实际的反斜杠字符。
  • 我认为很有可能(正如其他一些人指出的那样)您的实际字符串中没有反斜杠.您只是看到反斜杠,因为您正在打印它的 repr,它添加了 \\ 字符来转义字符串中的 \'。请注意,如果您打印包含字符串的列表/dict/etc,它将显示字符串的repr,以便将其与其余格式消除歧义。
  • @Quxntin:请提供minimal reproducible example。作为这里的新用户,也请收下tour并阅读How to Ask

标签: python


【解决方案1】:

字符串中没有反斜杠。您在表示字符串的 escape character 表示单引号是文字,并且不标记字符串的结尾。如果你打印字符串,你会看到。

s = '"Noir c\'est noir", ont-ils dit, y a donc vraiment plus d\'espoir'
print(s)

输出:

"Noir c'est noir", ont-ils dit, y a donc vraiment plus d'espoir

为了进一步说明,创建相同字符串的另一种方法是使用三引号且不使用反斜杠:

s = '''"Noir c'est noir", ont-ils dit, y a donc vraiment plus d'espoir'''
print(s)

我们得到相同的输出:

"Noir c'est noir", ont-ils dit, y a donc vraiment plus d'espoir

如果我们print(@987654322@(s)),我们将得到与原始相同的表示:

'"Noir c\'est noir", ont-ils dit, y a donc vraiment plus d\'espoir'

相关问题:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-20
    • 1970-01-01
    • 2017-03-02
    • 2015-09-25
    • 1970-01-01
    • 1970-01-01
    • 2016-11-20
    • 2017-12-09
    相关资源
    最近更新 更多