我使用来读取我的Python代码的参数。其中一个输入是可包含Unicode字符的文件标题[title
]。我一直在使用22少女時代22
作为测试字符串。Python的Unicode编码
我需要输入title
的值写入文件,但是当我尝试将字符串转换为UTF-8
它总是抛出一个错误:
UnicodeDecodeError: 'ascii' codec can't decode byte 0x8f in position 2: ordinal not in range(128)
我一直环顾四周,看到我需要我的字符串将以u"foo"
的形式在其上调用.encode()
。
当我在我的输入运行type()
从我看到:
<type 'str'>
我希望得到的响应:
<type 'unicode'>
我怎样才能得到它在正确的形式?
理念:
修改采取一个str
,但其存储为Unicode字符串u"foo"
:
parser.add_argument(u'title', metavar='T', type=unicode, help='this will be unicode encoded.')
这种做法是行不通的。思考?
编辑1:
一些示例代码,其中title
是22少女時代22
:
inputs = vars(parser.parse_args())
title = inputs["title"]
print type(title)
print type(u'foo')
title = title.encode('utf8') # This line throws the error
print title
输入数据是什么编码? –
@MarkTolonen好的,我会编辑我的帖子。 – Morrowind789