Unicode语法XlsxWriter Python 2模块中的歧义

时间:2014-03-25 23:54:36

标签: python-2.7 unicode

我现在正在使用python 2.7.6并使用XslxWriter模块将一些数据写入excel文件。我有一些存储在列表中的unicode数据。当我尝试使用根据文档的说明将数据保存到文件时,我有一些麻烦。 该指令发现here

指令说当你想要使用带有unicode字符串和python 2的模块时,你必须在第一个字符串中键入 u !我尝试使用简单的字符串,例如محسن。结果很好。

但是当我尝试执行此操作时,我的数据位于列表中,解释器尝试将其识别为具有新名称的变量,例如 ufoo 。当空格断开那些时,解释器将 u 识别为未知变量(也尝试连接 + 发生此问题) 我有点困惑。无论如何要解决这种模糊性?

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

我使用函数decode。

tip = 'Haz clic aquí para acceder al fichero remoto.'
tip = tip.decode('utf-8')

在python 2中使用decode的一个例子

import xlsxwriter

# Create a new workbook and add a worksheet
workbook = xlsxwriter.Workbook('hyperlink.xlsx')
worksheet = workbook.add_worksheet('Hyperlinks')

# Format the first column
worksheet.set_column('A:A', 30)

# Add the standard url link format.
url_format = workbook.add_format({
        'font_color': 'blue',
        'underline':  1
})

# Add a sample alternative link format.
red_format = workbook.add_format({
        'font_color': 'red',
        'bold':       1,
        'underline':  1,
        'font_size':  12,
})

# Add an alternate description string to the URL.
string = 'Grabación'
string = string.decode('utf-8')

# Add a "tool tip" to the URL.
tip = 'Haz clic aquí para acceder al fichero remoto.'
tip = tip.decode('utf-8')

# Write some hyperlinks
worksheet.write_url('A15', 'external://ordenador-remoto/Directorio/fichero.wav', red_format, string, tip)

workbook.close()