1秒登錄
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) 這種的?
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')
本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。