python : how to cast or convert string in a variable into raw -


x=''' print '\tone \'piece\' of \"metal\" \\sharp\\ edge ' print '\nthanks' ''' exec(x) 

i have string variable (x) , want use exec() print out correctly. if have access variable can directly use r' , problem solved, such :

x=r''' print '\tone \'piece\' of \"metal\" \\sharp\\ edge ' print '\nthanks' ''' exec(x) 

but in case , don't have access variable. string variable come other end or other user. how can apply r' existing variable can use exec() .

the correct output should :

    1 'piece' of "metal" \sharp\ edge   

the real case :

inside software, can create objects , each object can have properties such text input , button. refer text input , button properties object.text_input , object.button. let have 2 objects named aa , bb , type expression/script in aa.text_input (the text input of object1). bb (object2) want use expression entered in aa.text_input , execute using exec(). in bb.button write code such : exec(aa.text_input). data grab aa string. problem code type in text input of aa may contain character including escape chars , others. when use exec() in bb have error because of chars. question : how bring string bb.text_input correctly aa ?

as far understand, once 'x' declared losing memory of characters typed in, e.g. replaces '\n' newline character.

the way can think of reverting write statement replace characters in x original characters.

for example:

for char in x:     if char == '\n':          #replace '\\n' 

edit: 1 way this, example,

x = x.replace('\\', '\\\\') x = x.replace('\n', '\\n') x = x.replace('\t', '\\t') x = x.replace('\"', '\\\"') x = x.replace('\'', '\\\'') 

Comments

Popular posts from this blog

python Tkinter Capturing keyboard events save as one single string -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

javascript - Z-index in d3.js -