铸造原始字符串python [英] casting raw strings python
本文介绍了铸造原始字符串python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给定一个包含字符串的变量,是否有一种快速的方法可以将其转换为另一个原始字符串变量?
Given a variable which holds a string is there a quick way to cast that into another raw string variable?
以下代码应该说明我所追求的:
The following code should illustrate what I'm after:
line1 = "hurr..\n..durr"
line2 = r"hurr..\n..durr"
print(line1 == line2) # outputs False
print(("%r"%line1)[1:-1] == line2) # outputs True
到目前为止我发现的最接近的是 %r
格式化标志,它似乎返回原始字符串,尽管在单引号内.有没有更简单的方法来做这种事情?
The closest I have found so far is the %r
formatting flag which seems to return a raw string albeit within single quote marks. Is there any easier way to do this kind of thing?
推荐答案
Python 3:
"hurr..\n..durr".encode('unicode-escape').decode()
Python 2:
"hurr..\n..durr".encode('string-escape')
这篇关于铸造原始字符串python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文