13

I wrote a piece of code to convert PHP's striplashes into valid Python [backslash] escapes:

cleaned = stringwithslashes
cleaned = cleaned.replace('\\n', '\n')
cleaned = cleaned.replace('\\r', '\n')
cleaned = cleaned.replace('\\', '')

How can I condense it?

4

5 回答 5

13

不完全确定这是你想要的,但是..

cleaned = stringwithslashes.decode('string_escape')
于 2008-08-17T12:15:13.170 回答
3

听起来你想要的东西可以通过正则表达式合理有效地处理:

import re
def stripslashes(s):
    r = re.sub(r"\\(n|r)", "\n", s)
    r = re.sub(r"\\", "", r)
    return r
cleaned = stripslashes(stringwithslashes)
于 2008-08-17T12:55:25.100 回答
1

利用decode('string_escape')

cleaned = stringwithslashes.decode('string_escape')

使用

string_escape:在 Python 源代码中生成一个适合作为字符串文字的字符串

或像威尔逊的回答一样连接 replace() 。

cleaned = stringwithslashes.replace("\\","").replace("\\n","\n").replace("\\r","\n")
于 2014-02-18T19:02:19.183 回答
0

You can obviously concatenate everything together:

cleaned = stringwithslashes.replace("\\n","\n").replace("\\r","\n").replace("\\","")

Is that what you were after? Or were you hoping for something more terse?

于 2008-08-17T01:26:52.043 回答
-4

Python 有一个类似于 PHP 的 addlashes 的内置 escape() 函数,但没有 unescape() 函数(stripslashes),这在我看来有点荒谬。

正则表达式救援(代码未经测试):

p = re.compile( '\\(\\\S)')
p.sub('\1',escapedstring)

理论上,它采用 \\(not whitespace) 形式并返回 \(same char)

编辑:经过进一步检查,Python 正则表达式被彻底破坏了;

>>> escapedstring
'This is a \\n\\n\\n test'
>>> p = re.compile( r'\\(\S)' )
>>> p.sub(r"\1",escapedstring)
'This is a nnn test'
>>> p.sub(r"\\1",escapedstring)
'This is a \\1\\1\\1 test'
>>> p.sub(r"\\\1",escapedstring)
'This is a \\n\\n\\n test'
>>> p.sub(r"\(\1)",escapedstring)
'This is a \\(n)\\(n)\\(n) test'

总之,到底是什么,Python。

于 2008-08-17T10:28:00.967 回答