Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/313.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将变量传递给unicode/raw(ur";)转换函数_Python_Text_Unicode - Fatal编程技术网

Python 如何将变量传递给unicode/raw(ur";)转换函数

Python 如何将变量传递给unicode/raw(ur";)转换函数,python,text,unicode,Python,Text,Unicode,在获取实际文本时,我可以执行以下功能: In [7]: str = ur"FOO 20\N40%" In [8]: str Out[8]: u'FOO 20\\N40%' 但在实际情况中,单词“FOO 20\N40%”存储在变量mystring中。 怎么做?我试过了,但失败了: In [13]: mynewstr = ur(mystr) --------------------------------------------------------------------------- Na

在获取实际文本时,我可以执行以下功能:

In [7]: str = ur"FOO 20\N40%"

In [8]: str
Out[8]: u'FOO 20\\N40%'
但在实际情况中,单词
“FOO 20\N40%”
存储在变量
mystring
中。 怎么做?我试过了,但失败了:

In [13]: mynewstr = ur(mystr)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-13-0379c497611f> in <module>()
----> 1 mynewstr = ur(mystr)

NameError: name 'ur' is not defined
[13]中的
:mynewstr=ur(mystr)
---------------------------------------------------------------------------
NameError回溯(最近一次呼叫上次)
在()
---->1 mynewstr=ur(mystr)
名称错误:未定义名称“ur”

如果源字符串像您的示例那样仅由ASCII字符组成,则很容易:

mynewstr = unicode(mystr)
否则,您需要知道原始字符串字节的编码,并使用该编码转换为unicode。例如,如果您知道来源是UTF-8:

mynewstr = mystr.decode('utf-8')
例如

>>> print mystring
FOO 20\N40%
>>> unicode(mystring)
u'FOO 20\\N40%'
>>> mystring.decode('utf-8')
u'FOO 20\\N40%'