python - How to pass a variable to unicode/raw (ur"") conversion function -
i have no problem performing following function when taking actual text:
in [7]: str = ur"foo 20\n40%" in [8]: str out[8]: u'foo 20\\n40%'
but in actual case word "foo 20\n40%"
stored in variable mystring
. whats way that? tried failed:
in [13]: mynewstr = ur(mystr) --------------------------------------------------------------------------- nameerror traceback (most recent call last) <ipython-input-13-0379c497611f> in <module>() ----> 1 mynewstr = ur(mystr) nameerror: name 'ur' not defined
if source string consists of ascii characters example does, it's easy:
mynewstr = unicode(mystr)
otherwise need know encoding of original string bytes , use convert unicode. e.g. if know source utf-8:
mynewstr = mystr.decode('utf-8')
e.g.
>>> print mystring foo 20\n40% >>> unicode(mystring) u'foo 20\\n40%' >>> mystring.decode('utf-8') u'foo 20\\n40%'
Comments
Post a Comment