Python 中用反斜杠替换字符串
我正在尝试用“\s”(文字 \s,而不是某种反斜杠转义)简单替换“”。这就是我认为应该发生的事情:
>>> 'asdf hjkl'.replace(' ', '\s')
'asdf\shjkl'
我这样做了:
>>> 'asdf hjkl'.replace(' ', '\s')
'asdf\\shjkl'
>>> 'asdf hjkl'.replace(' ', '\\s')
'asdf\\shjkl'
两者都没有返回我所期望的结果,而且我一生都无法理解发生了什么。我必须使用什么输入才能获得预期的输出?
I'm trying to do a simple replacement of " " with "\s" (the literal \s, not some sort of backslash escape). This is what I think should happen:
>>> 'asdf hjkl'.replace(' ', '\s')
'asdf\shjkl'
I did this:
>>> 'asdf hjkl'.replace(' ', '\s')
'asdf\\shjkl'
>>> 'asdf hjkl'.replace(' ', '\\s')
'asdf\\shjkl'
Neither returns what I expected, and I can't for the life of me understand what's going on. What input do I have to use to get my expected output?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你正在得到你想要的。它在 REPL 中看起来并非如此:
如您所见,那是一个字符,而不是两个。
尝试
打印
它:You're getting what you want. It just doesn't look that way in the REPL:
As you can see, that's one character, not two.
Try
print
ing it:仅显示结果,
尝试以下操作,
The result is only displayed,
try the following,