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

这种的?

"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


需要打印的实际case是当json包含一个原始字符串, 我这个道理。



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

我就去做这样的。



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

 

相关文章:

  • 2021-09-08
  • 2022-12-23
  • 2022-12-23
  • 2021-06-09
  • 2021-06-18
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-10-16
  • 2022-12-23
  • 2021-12-11
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案