【问题标题】:How to replace single qoute to backslash+single qoute in Python如何在Python中将单引号替换为反斜杠+单引号
【发布时间】:2014-03-10 21:14:01
【问题描述】:

需要将'替换为\' 但这就是我得到的:

>>> s = "It's nice to have an example"
>>> s.replace("'", "\\'")
"It\\'s nice to have an example"
>>> s.replace("'", "\'")
"It's nice to have an example"
>>> s.replace("'", "\\\'")
"It\\'s nice to have an example"

如何得到"It\'s nice to have an example"的结果?

【问题讨论】:

  • 你做对了。 Python 正在转义 ` again when it displays it, but the string itself is correct. Try print`ing 值,您会正确看到它。
  • 如果你想看看字符串打印时的样子...你为什么不print呢?请注意,交互式解释器打印字符串,它显示它的字符串表示形式(即它相当于print(repr(text)),注意额外的repr)。
  • 我只需要转义单个 qoute 并且我想在 repr 中获得单个反斜杠。因为当我序列化时,我得到了我的 javascript 代码:SmObj.initialize('[{"description": "My belgian sheepdog! Isn\\'t she cute?", "author": {"username": "Marabesta", "get_full_name": "Olga Smith"}, {...}, ...]');

标签: python regex replace


【解决方案1】:

你已经做对了,但是字符串的representation 让你失望了。试试:

print s.replace("'", "\\'")
=>  It\'s nice to have an example

如果您不使用print,则会显示结果字符串的repr(而不是其str),并且在此repr 中,反斜杠被转义,从而产生双反斜杠。

this question,关于__str____repr__


EDIT -- 因为您在评论中提到您需要一个可以在 javascript 中使用的字符串...

使用json.dumps(),而不是repr

【讨论】:

  • 但是我怎样才能在repr 中获得一个反斜杠?
  • 你需要它做什么? print 就是你想要的
【解决方案2】:

您可以将encodestring-escape 编码一起使用:

>>> s = "It's nice to have an example"
>>> s = s.encode('string-escape')
>>> print s
It\'s nice to have an example

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-27
    • 2014-09-25
    • 2011-12-25
    • 2017-09-14
    • 1970-01-01
    • 1970-01-01
    • 2018-02-13
    • 1970-01-01
    相关资源
    最近更新 更多