Python中转换原始字符串
假设你有一个变量,它里面存的是一段字符串,想要快速把它转换成另一个原始字符串变量,有没有简单的方法呢?
下面的代码可以帮你说明我想要的效果:
line1 = "hurr..\n..durr"
line2 = r"hurr..\n..durr"
print(line1 == line2) # outputs False
print(("%r"%line1)[1:-1] == line2) # outputs True
我找到的最接近的方法是使用 %r
这个格式化标志,它似乎能返回一个原始字符串,不过是带着单引号的。有没有更简单的方法可以做到这一点呢?
3 个回答
1
上面展示了如何进行编码。
'hurr..\n..durr'.encode('string-escape')
这样可以进行解码。
r'hurr..\n..durr'.decode('string-escape')
举个例子。
In [12]: print 'hurr..\n..durr'.encode('string-escape')
hurr..\n..durr
In [13]: print r'hurr..\n..durr'.decode('string-escape')
hurr..
..durr
这让我们可以在两个方向上“转换原始字符串”。一个实际的例子是,当json里有一个原始字符串时,我想把它打印得更好看。
{
"Description": "Some lengthy description.\nParagraph 2.\nParagraph 3.",
...
}
我会这样做。
print json.dumps(json_dict, indent=4).decode('string-escape')
2
还有一种方法:
>>> s = "hurr..\n..durr"
>>> print repr(s).strip("'")
hurr..\n..durr
85
Python 3:
"hurr..\n..durr".encode('unicode-escape').decode()
Python 2:
"hurr..\n..durr".encode('string-escape')