Fork me on GitHub

强制转换原始字符串python (转)

http://qa.helplib.com/874184

给定一个, 该变量来保存字符串在python中, 有快速转换到另一个原始str变量的方法吗?

下面的代码应该阐明im后- -



def checkEqual(x, y):
    print True if x==y else False

line1 = "hurr..\n..durr"
line2 = r"hurr..\n..durr"
line3 = "%r"%line1

print "%s \n\n%s \n\n%s \n" % (line1, line2, line3)

checkEqual(line2, line3)        #outputs False

checkEqual(line2, line3[1:-1])  #outputs True

最近的到现在为止, 我发现%r格式化标志它似乎返回一个原始字符串尽管在单个引号。 是否有简单的方法来完成该像 line3 = raw(line1) 这种的?

"hurr..\n..durr".encode('string-escape')

好这显然是一种简单的方法。 我将这里解决方案中用于比较的份以上。


escape_dict={'\a':r'\a',
           '\b':r'\b',
           '\c':r'\c',
           '\f':r'\f',
           '\n':r'\n',
           '\r':r'\r',
           '\t':r'\t',
           '\v':r'\v',
           '\'':r'\'',
           '\"':r'\"',
           '\0':r'\0',
           '\1':r'\1',
           '\2':r'\2',
           '\3':r'\3',
           '\4':r'\4',
           '\5':r'\5',
           '\6':r'\6',
           '\7':r'\7',
           '\8':r'\8',
           '\9':r'\9'}

def raw(text):
    """Returns a raw string representation of text"""
    new_string=''
    for char in text:
        try: new_string+=escape_dict[char]
        except KeyError: new_string+=char
    return new_string


上了另一种方法
> > >  s = "hurr..\n..durr"
> > >  print repr(s).strip("'")
hurr..\n..durr


> > >  v1 = 'aa\1.js'
> > >  re.sub(r'(.*)\.js', repr(v1).strip("'"), 'my.js', 1)
'aa\\x01.js


But



> > >  re.sub(r'(.*)\.js', r'aa\1.js', 'my.js', 1)
'aamy.js'

And



> > >  re.sub(r'(.*)\.js', raw(v1), 'my.js', 1)
'aamy.js'

和更好的原始方法实现



def raw(text):
    """Returns a raw string representation of text"""
    return "".join([escape_dict.get(char,char) for char in text])
 
上面所显示如何编码。


'hurr..\n..durr'.encode('string-escape')

按这种方式解码。



r'hurr..\n..durr'.decode('string-escape')

ex 。



In [12]: print 'hurr..\n..durr'.encode('string-escape')
hurr..\n..durr

In [13]: print r'hurr..\n..durr'.decode('string-escape')
hurr..
..durr


这允许一个" 投射/ trasform原始字符串" 在两个方向。 需要打印的实际case是当json包含一个原始字符串, 我这个道理。



{
    "Description": "Some lengthy description.\nParagraph 2.\nParagraph 3.",
    ...
}

我就去做这样的。



print json.dumps(json_dict, indent=4).decode('string-escape')

 

posted on 2016-02-25 17:53  pengyingh  阅读(2445)  评论(0)    收藏  举报

导航