在python中使用xlrd从xls中提取数据

我试图从一个.xls文件中提取数据并创build一个列表,但是我得到的列表是[u'elem1', u'elem2', u'elem3'] ,但是如果我单独打印,我会得到:

 elem1 elem2 elem3 

你是什​​么东西,如何去除它?

这是我的代码…

 from xlrd import open_workbook xls=open_workbook('name.xls') for sheets in xls.sheets(): list1=[] for col in range(sheets.ncols): for rows in range(sheets.nrows): list1.append(sheets.cell(rows, col).value) print(list1) for i in list1: print(i) 

您可以将文本定义为string,同时将数据追加到list1.append(str(sheets.cell(rows,col).value))的列表中以删除[u' 。代码将为:

  from xlrd import open_workbook xls=open_workbook('name.xls') for sheets in xls.sheets(): list1=[] for col in range(sheets.ncols): for rows in range(sheets.nrows): list1.append(str(sheets.cell(rows, col).value)) print(list1) for i in list1: print i 

假设你使用的是Python 2.x,那么u就说xlrd为你提供了unicodestring(真正的Excelstring)。 如果你想用Python 2.7string来转换它们,你必须用你使用的字符集进行编码

假设您使用latin1(也称为iso-8859-1或windows-1252(差别很小)),则可以使用latin1string列表将您的unicodestring列表转换为以下方式:

 strlist = [ elt.encode('latin1') for elt in list1 ] 

或者只有ASCII字符

 strlist = [ str(elt) for elt in list1 ] 

我通过这样做来解决它

 str(variable_name) 

实际上, u一开始就不会影响你。 U也可以和他们一起工作,除非你有一些与以不同格式编码有关的问题。