我写了一段代码PHP的striplashes转换成有效的Python [反斜线]转义:
cleaned = stringwithslashes
cleaned = cleaned.replace('\\n', '\n')
cleaned = cleaned.replace('\\r', '\n')
cleaned = cleaned.replace('\\', '')
我怎样才能凝结吗?
我写了一段代码PHP的striplashes转换成有效的Python [反斜线]转义:
cleaned = stringwithslashes
cleaned = cleaned.replace('\\n', '\n')
cleaned = cleaned.replace('\\r', '\n')
cleaned = cleaned.replace('\\', '')
我怎样才能凝结吗?
不能完全确定这是你想要的,但..
cleaned = stringwithslashes.decode('string_escape')
这听起来像你想可以合理有效地通过正则表达式处理的内容:
import re
def stripslashes(s):
r = re.sub(r"\\(n|r)", "\n", s)
r = re.sub(r"\\", "", r)
return r
cleaned = stripslashes(stringwithslashes)
你可以明显地串连在一起的一切:
cleaned = stringwithslashes.replace("\\n","\n").replace("\\r","\n").replace("\\","")
那是你所追求的? 还是你希望的东西更简洁?
使用decode('string_escape')
cleaned = stringwithslashes.decode('string_escape')
运用
string_escape:产生一个字符串,它是适合作为字符串中Python源代码字面
或连接替换()之类Wilson's答案。
cleaned = stringwithslashes.replace("\\","").replace("\\n","\n").replace("\\r","\n")
Python有一个内置的escape()函数类似PHP的addslashes的,但没有UNESCAPE()函数(的stripslashes),它在我心目中是很荒谬。
正则表达式来救援(代码未测试):
p = re.compile( '\\(\\\S)')
p.sub('\1',escapedstring)
在理论的形式为\\(没有空格),返回任何\(相同字符)
编辑:在进一步的检查,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'
总之,什么是地狱,巨蟒。