【问题标题】:How to replace single forward slashes with single backward slashes如何用单个反斜杠替换单个正斜杠
【发布时间】:2020-10-02 00:03:43
【问题描述】:

考虑一个包含带有一些正斜杠的任意字符串的 python 变量。我想 用反斜杠替换字符串中的每个正斜杠。这些正斜杠出现 在输入字符串中而不是在路径分隔符的上下文中。

我找不到使用 python 的字符串 'replace' 方法进行此替换的方法。

使用单个反斜杠作为第二个参数会产生语法错误作为单个反斜杠 转义终止引号

>>> s = 'a26/n//3@5'
>>> s
'a26/n//3@5'
>>> s.replace('/', '\')
  File "<stdin>", line 1
    s.replace('/', '\')
                      ^
SyntaxError: EOL while scanning string literal

在替换字符串中使用两个单反斜杠会在输出字符串中产生两个反斜杠

>>> s.replace('/', '\\')
'a26\\n\\\\3@5'

被替换的字符串应该包含

a26\n\\3@5

【问题讨论】:

  • "在替换字符串中使用两个单反斜杠会在输出字符串中产生两个反斜杠"不,它不会。

标签: python-3.x


【解决方案1】:

您看到的输出是字符串的repr 表示。

>>> s = 'a26/n//3@5'
>>> s
'a26/n//3@5'
>>> s.replace('/', '\\')
>>> s
>>> 'a26\\n\\\\3@5' # repr representation ('\' as '\\')

要获得预期的输出,您应该 print 字符串:

>>> new_s = s.replace('/', '\\')
>>> print(new_s)
>>> a26\n\\3@5

编辑:修正错字

【讨论】:

  • 替换函数结束后多了一个)
  • 如果解释器调用repr方法显示,不清楚为什么这两条语句产生不同的输出>>> new_s 'a26\\n\\\\3@5' >>> repr( new_s) "'a26\\\\n\\\\\\\\3@5'" 另外,print(new_s) 与 new_s.__str__() 不同,否则,我们会在这些语句中得到相同的输出下面 >>> print(new_s) a26\n\\3@5 >>> new_s.__str__() 'a26\\n\\\\3@5'
猜你喜欢
  • 2012-05-17
  • 2023-03-16
  • 2018-06-07
  • 2020-01-17
  • 2012-06-16
  • 1970-01-01
  • 1970-01-01
  • 2010-09-11
  • 1970-01-01
相关资源
最近更新 更多